[TypeScript] Initialize a TypeScript Node.js project
TypeScript Node.js Project
TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale.
Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine.
This article is about how to setup Typescript project from scratch.
Prerequisites
-
Node.js - https://nodejs.org/en/
Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine.
Install Node.js - https://nodejs.org/en/ CLI.
1
2Mac OS X
brew install nodeSee Node.js - https://nodejs.org/en/ to learn more about others OS.
Create a node project using npm
1 | npm init -y |
Install Typescript dependencies
1 | npm i --save-dev typescript ts-node nodemon |
Dependencies:
-
typescript
is for Typescript language itself and compiling tool -
ts-node
is used to run Typescript without compiling -
nodemon
is used to run/restart node automatically when files changed
Initialize tsconfig.json
Creates a tsconfig.json
in your project folder. This controls the strictness/settings in Typescript files
1 | npx tsc --init |
Adjust tsconfig [optional]
Some basic settings in tsconfig.json
that are recommended are:
1 | { |
Common Compiler Options:
-
experimentalDecorators
true enables experimental support for decorators - https://github.com/tc39/proposal-decorators, which is in stage 2 of the TC39 standardization process. -
forceConsistentCasingInFileNames
true TypeScript will issue an error if a program tries to include a file by a casing different from the casing on disk. -
module
Sets commonjs as the module system for the program. See the Modules - https://www.typescriptlang.org/docs/handbook/modules.html reference page for more information. You very likely want “CommonJS” for node projects. -
moduleResolution
node specify TypeScript looks up a file from Node.js’ CommonJS implementation. -
noFallthroughCasesInSwitch
true report errors for fallthrough cases in switch statements. -
noImplicitReturns
true will check all code paths in a function to ensure they return a value. -
outDir
redirects output structure to the directory -
pretty
true stylize errors and messages using color and context, this is on by default. -
strict
true enables all strict type-checking options -
target
es2016 as es6 helps to support es6 code -
sourceMap
true generates corresponding.map
file -
rootDir
specifies the root directory of input files -
declaration
true generates corresponding.d.ts
file
See TypeScript: TSConfig Reference - Docs on every TSConfig option - https://www.typescriptlang.org/tsconfig to learn more.
Testing
1 | echo "console.log('Hello typescript !')" > index.ts |
Add scripts to package.json
1 | { |
Run npm run start
to start application without compile.
Run npm run build
then node dist/index.js
to compile and run applcation as javascript.
References
[6] https://262.ecma-international.org/7.0/ - https://262.ecma-international.org/7.0/