1. Home
  2. Web Development
  3. How to add TypeScript to an existing Node.js project

How to add TypeScript to an existing Node.js project

Share

If you have an old Node.js project written in JavaScript, it’s definitely the case to upgrade your development environment and add TypeScript. Why should you use TypeScript? The answer is simple: TypeScript is more reliable and easier to refactor, it makes the types explicit and more suitable for large-scale projects.

That’s said, let’s now see how to add TypeScript to an existing Node.js project in just a few simple steps.

Prerequisites

To get started you need to have Node.js and NPM installed. To install Node.js and NPM you can go to the official Node.js download page. After completing the installation of Node.js and NPM, we must have an NPM project initialized and install the TypeScript dependencies.

Inizialize NPM project

If you don’t already have an existing project, we need to initialize a new NPM project. First, to initialize a new NPM project we need to create a new folder by using the command:

mkdir my-new-node-project
cd my-new-node-project

At this point, we need to initialize the project using the command:

npm init -y

This will create a new package.json file where NPM will save every production and development dependencies. If we are using git as source control, we also want to ignore the node_modules folder where NPM will download every dependency. To do so, create a .gitignore file and paste the following into it:

# NPM dependencies
node_modules

# If using vscode
.vscode

Add TypeScript dependencies for Node.js

To add TypeScript in a Node.js project we need to install some dependencies. First, we need to add TypeScript running the following command:

npm install --save-dev typescript

Now, we need to add the types for every dependency we already have installed in our project, along with the Node.js type itself.

To add the Node types, run:

npm install --save-dev @types/node

You should now install the types for every dependency you already installed in your project. For example, if you are using node-fetch, you can add the types with the following command:

npm install --save-dev @types/node-fetch

Configure TypeScript for Node.js project

Firstly, we need to configure TypeScript to work in our project. TypeScript requires the tsconfig.json file in the project path, where we will store the compiler configuration.

The configuration we need to get started with TypeScript in Node.js is pretty simple: create the tsconfig.json file in the root of your project and paste the following code:

{
  "compilerOptions": {
    "target": "es6", 
    "module": "commonjs", 
    "sourceMap": true, 
    "outDir": "./dist", 
    "strict": true, 
    "moduleResolution": "node", 
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true 
  }
}

At this point, the last configuration required is to update our package.json file where we will change the start script to compile and run our TypeScript files.

To do so, open your package.json file what should look similar to the code below, and edit the start script:

{
  "name": "my-new-node-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "tsc && node dist/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "node-fetch": "^2.6.1",
    "typescript": "^4.2.3"
  },
  "devDependencies": {
    "@types/node": "^14.14.35",
    "@types/node-fetch": "^2.5.8"
  }
}

If you are adding TypeScript to an existing project and your main file has another name, override “index.js” with the name of your JavaScript entry point file (usually it may also be app.js, main.js, …).

Node.js with TypeScript example

At this point, we should be able to easily run our existing Node.js project with TypeScript. In the following snippet, you can see a really basic example of a Node.js script that uses TypeScript and node-fetch:

import fetch from 'node-fetch'
import fs from 'fs'

async function fetchUrl(url: string) {
  return fetch(url).then((r) => r.text())
}

;(async () => {
  const response = await fetchUrl('https://www.google.com')
  fs.writeFileSync('./google.html', response, { encoding: 'utf-8' })
  process.exit(0)
})()
If you like our post, please share it:

Polynique © 2020 - 2021, made with ❤️ by a developer, for developers.

Latest update:

All trademarks, service marks and company names are the property of their respective owners.

AboutPrivacy PolicyCookie Policy