How to Set up Node.js with Typescript

sungminkim0508

Sungmin

Posted on September 30, 2020

How to Set up Node.js with Typescript

First thing first, we need to install all packages for typescript.

Install Packages

yarn add -D @types/node typescript
yarn add ts-node
Enter fullscreen mode Exit fullscreen mode

@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"
}
Enter fullscreen mode Exit fullscreen mode

We also need to create tsconfig.json to understand .ts file and set up compiler options.

npx tsconfig.json
Enter fullscreen mode Exit fullscreen mode

It will ask you what framework you are using. I will choose node.

Alt Text

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
Enter fullscreen mode Exit fullscreen mode

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

  1. Compiler compiles typescript files and run the app, which it is slow to execute.
  2. 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",
  ...
}
Enter fullscreen mode Exit fullscreen mode

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"
      ...
  }
}

Enter fullscreen mode Exit fullscreen mode

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"
  ...
}
Enter fullscreen mode Exit fullscreen mode

Open two terminals and run yarn watch and yarn dev. And you will see compiler is running .js files that transfiled from .ts.

šŸ’– šŸ’Ŗ šŸ™… šŸš©
sungminkim0508
Sungmin

Posted on September 30, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related