Our team has js based node.js project. As our project getting bigger and bigger, we started to need Typescript like other team…
Why do we need Typescript
- Javascript is good for the first draft. You don’t need to think that much. But when it comes to refactoring, things are much harder thant Typescript especially when codes are large and lengthy.
- Type hinting (link)
- Faster & easy development
Okay… so what do we need?
Things to know
- Typescript transpiler is named “tsc”
- Node can only run Javascript code so wee need plugin called “ts-node” to achieve Typescript support.
- Running code and transpiling code are two different things.
- Existing modules need @types.
Basically, we write code in .ts. And using typescript compiler like tsc, we get js file.With the help of “ts-node” we don’t even need to compile the ts just run instead.
Let’s get started
1
2
npm i -g typescript // Install it to current pc
npm i typescript // Install it to local(current folder)
1
npm i -D express ts-node nodemon @types/node @types/express
1
2
3
4
5
6
7
8
9
10
11
{
"compilerOptions": {
"target": "es6",
"module": "commonjs", // Set which module method to compile
"outDir": "./dist", // This is where js files are created after compilation.
"rootDir": "./src", //Root folder
"strict": true,
"moduleResolution": "node", // Set iterpretation method for module
"esModuleInterop": true
}
}
1
2
3
4
5
6
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node dist/index.js",
"build": "tsc -p .",
"dev": "nodemon --watch \"src/**/*.ts\" --exec \"ts-node\" src/index.ts"
}