How to Set up Node.js with Typescript
Sungmin
Posted on September 30, 2020
First thing first, we need to install all packages for typescript.
Install Packages
yarn add -D @types/node typescript
yarn add ts-node
@types/node
: contains all type for Node.js.
typescript
: supports typescript on the app.
ts-node
: tool that read typescript files.
Add start
script on package.json
"scripts": {
"start": "ts-node src/index.ts"
}
We also need to create tsconfig.json
to understand .ts
file and set up compiler options.
npx tsconfig.json
It will ask you what framework you are using. I will choose node
.
Let's run typescript. We are going to run the .ts
file without transpiling. Create src/index.ts
and type like this
console.log('hello world') // hello world
and run command yarn start
. And you will see hello world
on the console.
Add tsc -w
on package.json
When you run typescript files, there are a coule of things you worry about
- Compiler compiles typescript files and run the app, which it is slow to execute.
- You are not sure what bugs come out before you transpile
.ts
especially when you build the production code.
So what I am going to do is transpiling the .ts
to .js
, and run only .js
file, not .ts
Open package.json and add watch
flag
// package.json
"scripts": {
"watch": "tsc -w",
...
}
tsc -w
command is one of Typescript CLI command and simply transpiles .ts
files and generate .js
files.
But you need to tell Typescript CLI in which folders you are going to put .js
files transpiled by tsc -w
command.
So open tsconfig.json
and add option "outDir": "./dist"
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"lib": [
"dom",
"es6",
"es2017",
"esnext.asynciterable"
],
...
"outDir": "./dist"
...
}
}
You can change the directory whenever you want. You just change "outDir": "yourDir"
.
Okay. Let's try this out. Open package.json
and add dev
script like this.
// package.json
"scripts": {
"watch": "tsc -w",
"dev": "node dist/index.js"
...
}
Open two terminals and run yarn watch
and yarn dev
. And you will see compiler is running .js
files that transfiled from .ts
.
Posted on September 30, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.