I used to work on traditional plain javascript code while working on node js. It caused a lot of problems as
- Forget how to use the methods, classes or objects that we built into a module long time ago
- When a project becomes larger, bugs mostly comes from a minor mistake which typescript helps eliminating
So, I learned how to setup typescript project from scratch
Create a node project using npm
PROJECT_NAME = <project name>
mkdir $PROJECT_NAME && cd $PROJECT_NAME
npm init -y
Install typescript dependencies
npm i --save-dev typescript ts-node nodemon
- 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
npx tsc --init
This creates a tsconfig.json in your project folder. This controls the strictness/settings in typescript files
Adjust tsconfig [optional]
Some basic settings in tsconfig.json
that are recommended are
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"declaration": true,
"sourceMap": true,
"outDir": "dist",
"rootDir": "./",
"strict": true,
"esModuleInterop": true
}
}
- setting
target
as es6 helps to support es6 code - setting
declaration
true generates corresponding '.d.ts' file - setting
sourceMap
true generates corresponding '.map' file -
outDir
redirects output structure to the directory -
rootDir
specifies the root directory of input files - setting
strict
true enables all strict type-checking options
Add program for testing
echo "console.log('Hello typescript !')" > index.ts
Add scripts to package.json
{
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"start": "ts-node index.ts",
"build": "tsc"
},
}
- execute
npm run start
to start application without compile - execute
npm run build
thennode dist/index.js
to compile and run applcation as javascript
Top comments (1)
I like how your article is straight to the point. and you let us know what each dependency does in a single sentence. Good stuff!!