Best Setup to Use TypeScript with Node.js and Express Project

Robin
April 15, 2022

It is very easy to set up TypeScript with Node.js and Express projects. There are a few steps you need to follow to get the best setup for any Node.js project.

Why should you use TypeScript with Node.js and Express?

Node.js is a runtime that uses JavaScript to create web servers. It provides a better developer experience because in both front-end and backend we can use the same language.

But when your application gets bigger or you need a team of developers who work together then you can make use to TypeScript instead of using JavaScript. Because TypeScript comes with type safety and some additional features that can give ease of development.

Therefore in this article, I will show you the best setup for a Node.js and Express project with TypeScript. You can use this setup for any of your future projects.

Before starting, I would highly suggest that you should have the following:

  • Install at least the Node.js version 12.X or above locally on your computer.
  • You should have a package manager like npm or Yarn.
  • Basic knowledge of Node.js, Express, and TypeScript.
  • You should know how to use the terminal to run simple commands.

How to Setup TypeScript with Node.js and Express Project

To have a complete setup for your Node.js and Express project with TypeScript you need to follow 7 simple steps. This way you can create a boilerplate so that you can use it for your future project.

Here are the 7 simple steps to have the best TypeScript setup for a Node.js and Express project:

  1. Create a package.json file.
  2. Create a tsconfig.json file.
  3. Install packages for Node.js and Express.
  4. Install TypeScript in the Node.js project.
  5. Create an Express server using TypeScript.
  6. Configure TypeScript settings.
  7. Add scripts in the package.json file to build and run the project.

Let's see every step in detail

Best Setup to Use Typescript with Node.js and Express Project

Step 1: Create package.json File

At first, we need to create a directory where we will keep our project files. Then inside that directory, we will create a package.json file. This file will store all of our scripts and track our installed packages.

          mkdir node-typescript-project
cd node-typescript-project
npm init --yes
        

I am creating a directory called node-typescript-project using mkdir command but you can name your directory whatever you like.

Then go inside your directory using the cd command. While creating your package.json file, you can use --yes flag to get all the default settings. Otherwise, you can define your setting manually without using --yes flag.

When you open your directory in a text editor, you can check your package.json file. With the default setting it will look something like this:

          {
  "name": "node-typescript-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "type": "module",
  "keywords": [],
  "author": "",
  "license": "ISC"
}
        

Step 2: Create tsconfig.json File

In this step, we will create the tsconfig.json file. It's a configuration file for TypeScript. TypeScript will use this file while compiling your project into JavaScript.

Before creating this file make sure you have installed TypeScript globally on your computer. You can also use TypeScript without installing it globally. But I would highly suggest you install it globally.

          tsc -v
        

You can check if your computer has TypeScript installed globally. The above command will show a version number if it is available. Otherwise, you can install the latest version using the following command.

          npm install -g typescript
        

When you have the TypeScript package installed in your system, you can use tsc command to generate a tsconfig.json file.

          tsc --init
        

The above command will generate the file with default compiler settings. For now, we will leave this file as it is with these default settings. later we will modify these settings for our project.

If you don't have TypeScript installed globally on your computer, you have to add npx with the previous command to generate a tsconfig.json file.

          npx tsc --init
        

Step 3: Installing Packages for Node.js and Express Boilerplate

Now we will install our necessary packages as dependencies and devDependencies for the project. We will install 2 packages as dependencies express and dotenv.

          npm install express dotenv
        

You can use the above npm command to install those packages:

We also need a few packages for the development as devDependencies. You can install them with the following command:

          npm install --save-dev nodemon ts-node
        

I am installing nodemon and ts-node packages. Here, the --save-dev flag is used to tell Node that these packages are not our main dependencies for the project.

  • nodemon - This package tracks changes in a project and restarts the server automatically. When you will update any code in your Node project, it will restart your server with the updated code.
  • ts-node - It is a TypeScript execution engine for Node. It is necessary for nodemon to execute your TypeScript files on Node.js without precompiling.

Step 4: Installing TypeScript in a Node.js Project

Even if you have installed TypeScript on your computer globally, it is necessary to install it locally for each project as a dev dependency. You also have to install the @types declaration packages for Express and Node.js because they don't come with type declaration files.

Type Declaration packages contain files with .d.ts extensions. These files describe all types present inside a JavaScript package for the TypeScript compiler. These type declaration files are available for all packages that are written in JavaScript. TypeScript packages don't need a type declaration file.

So, if a package is written in Typescript then there is no need to install a type declaration for it. You will find type declaration files for any JavaScript package in the DefinitelyTyped Github repository.

Therefore, you don't have to write them from scratch. There is an easy technique to find a type declaration for any package. You have to this @types/packageName pattern.

For example, if the package name is express then its type declaration will be @types/express. Every JavaScript package follows this pattern. So you don't have to memorize the type declaration package name.

          npm install --save-dev typescript @types/express @types/node
        

By running this command in your terminal, you can install these 3 packages. One is typescript and the other 2 are type declarations for express and node. With --save-dev flag, we are telling that these packages are dev dependencies.

You can open your package.json file to see the list of packages installed in your project. There you will find your packages are divided into 2 groups.

All main dependencies are inside the dependencies block and dev dependencies are indie the devDependencies block.

Step 5: Create an Express Server Using TypeScript

After installing all of our packages, let's create a simple Express server with TypeScript. At first, I will create a directory called src inside the node-typescript-project directory that I have created in step 1.

Inside the src directory, all of our TypeScript files will live. I will set up this directory as a root for our TypeScript files in the next step using tsconfig.json file.

Let's create app.ts file in the src directory. It will be the entry point of our Node.js application. Add the following code to the app.ts file.

          import { config } from 'dotenv';
import express, { Application, NextFunction, Request, Response } from 'express';

config();

const app: Application = express();

app.get('/', (req: Request, res: Response, next: NextFunction) => {
    res.send('Express server with TypeScript');
});

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
    console.log(`Server is listening on port ${PORT}`);
});

        

I am using dotenv package to load environment variables from a .env file. There is a function called config() in this package. You just have to import and call this function in order to load environment variables in the Node.js application.

          PORT=3000

        

I have created a .env file with the above code inside the node-typescript-project directory. As we are using the dotenv package, I can access the PORT variable using process.env.PORT in our application.

Also Read: Easiest Way to Set & Use Environment Variables (.env) in Node.js

I have imported express() from the express package which is a function. When you call this function, it will return an application with the type Application. You have to import this type from the express package.

Now using the application returned from express() function, you can create routes. Each route will have req, res, and next in its callback function. You have to import their types e.i. Request, Response, and NextFunction from the express package.

By adding these types, you will get code completion in your code editor.

Finally, we will listen to a port so that we can run our application in a browser. I am getting the port number from the environment variable using process.env.PORT. If it returns undefined then by default it will use 3000.

Step 6: Configure TypeScript Settings

Now, it's time to configure our TypeScript settings in the tsconfig.json file for the project. TypeScript compiler will use these settings to compile your project into JavaScript.

Inside this file, there is one mandatory field called compilerOptions. These are the options you should configure in this field:

  • target - Allows us to specify the target version of JavaScript that the compiler will output.
  • module - Specifies a module manager in the compiled JavaScript code. It supports CommonJS which is standard in Node.js
  • outDir - Sets an output directory where the compiler will store all compiled JavaScript files.
  • rootDir - Specifies the root directory of input files. All TypeScript files will live inside that directory.
  • strict - If it is set to true, it enables all strict type-checking options.
  • moduleResolution - Specify module resolution strategy.
  • esModuleInterop - It allows compiling ES6 modules to CommonJS modules in Node.js
  • skipLibCheck - If it is set to true, it will skip type checking of default library declaration files.
  • forceConsistentCasingInFileNames - If it is set to true, it will enable case-sensitive file naming.

When you remove all the comments from tsconfig.json file, it will look something like this:

          {
    "compilerOptions": {
        "target": "ES2015",
        "module": "commonjs",
        "outDir": "./dist",
        "rootDir": "./src",
        "strict": true,
        "moduleResolution": "node",
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true
    },
    "include": ["./src"]
}

        

By default, target is set to "es5" but I am setting it to "ES2015". If you want you can use any ECMAScript version.

As a rootDir, I am specifying the src directory that I have created. That means I am telling the compiler that all my TypeScript files will live inside this directory.

When we set a directory as our rootDir, we have to add an additional field beside compilerOptions field which is include.

This include field is an array. Here, we also have to specify the path of our src folder. In this way, the compiler will only compile TypeScript files that are inside this directory.

Otherwise, the compiler will also try to compile any TypeScript file outside the src directory and will give an error.

Step 7: Add Scripts to Build Node.js and TypeScript Project

In Node.js, scripts are the commands that are used to perform different tasks. You can add different scripts in the package.json file.

For this project, I will add 3 scripts:

  • build - It will build our project for production.
  • dev - It will run our project for development. If you update your code, it will automatically restart the server.
  • start - It will start the production server after we build our project using the build script.
            "scripts": {
    "build": "tsc",
    "dev": "nodemon ./src/app.ts",
    "start": "node ./dist/app.js"
  },

        

In the build script, you will specify tsc if you have TypeScript installed globally on your computer. Otherwise, you have to use npx tsc. It will compile our project to JavaScript and store it inside the ./dist directory. Because we specified this directory as outDir in the tsconfig.json file.

In the dev script, I am specifying the app.ts file inside the src directory. As it is a TypeScript file, nodemon package will also use the ts-node package in the background to compile it.

In the start script, I am running the app.js file inside the ./dist directory. We will only use this script after building our project.

  • npm run build - When you run this command in your terminal window, it will build your project.
  • npm run dev - This command will spin up a development server at http://localhost:3000. It will also restart your server when you change something in your code.
  • npm run start - It will start the production server at http://localhost:3000 after building your project.

Conclusion

You have successfully set Node.js and Express project with TypeScript. From now on you can use it as a boilerplate for any future Node.js project.

You just have to add the necessary packages and routes for your projects. You can use any TypeScript features. It will give you type safety and all other benefits that you get using TypeScript.

This is the best Node.js and Express setup with TypeScript that you can use for a project of any size.

I hope it was helpful for you. Thank you so much. Happy coding :)

Related Posts