[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:
-
typescriptis for Typescript language itself and compiling tool -
ts-nodeis used to run Typescript without compiling -
nodemonis 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:
-
experimentalDecoratorstrue enables experimental support for decorators - https://github.com/tc39/proposal-decorators, which is in stage 2 of the TC39 standardization process. -
forceConsistentCasingInFileNamestrue TypeScript will issue an error if a program tries to include a file by a casing different from the casing on disk. -
moduleSets 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. -
moduleResolutionnode specify TypeScript looks up a file from Node.js’ CommonJS implementation. -
noFallthroughCasesInSwitchtrue report errors for fallthrough cases in switch statements. -
noImplicitReturnstrue will check all code paths in a function to ensure they return a value. -
outDirredirects output structure to the directory -
prettytrue stylize errors and messages using color and context, this is on by default. -
stricttrue enables all strict type-checking options -
targetes2016 as es6 helps to support es6 code -
sourceMaptrue generates corresponding.mapfile -
rootDirspecifies the root directory of input files -
declarationtrue generates corresponding.d.tsfile
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/