Setup Typescript using Node.js and Express

Setting up Nodejs Express Typescript Server

  1. Setting up Nodejs Express Typescript Server
  2. Setting up a custom logger for node express typescript server
  3. Setup Code Linting in VSCode for Express Typescript Server with Eslint
  4. Configuring Tooling using ESLint, Editorconfig, Prettier and Husky
  5. Setting up React Client from scratch
  6. Configuring Monorepo with yarn workspaces and lerna
  7. Creating REST APIs using Node, Express, Typescript, Mongodb
  8. Configuring Typescript with React

In this tutorial, we will see how to setup nodejs express project with Typescript. As you know Typescript is a superset of Javascript, it enables lot of features in the core language. so Let’s get started :

  1. Let’s create a new node project
$ mkdir myapp
$ cd myapp
$ npm init -y 

This will create a new nodejs based project.

2. Setup express

$ npm install —S express body-parser cors nodemon

Lets create our index.js

import bodyParser from 'body-parser';
import express from 'express';

const app = express();
const PORT = process.env.PORT || 3000;

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

app.get('/', (req, res) => {
    res.status(200).send("Welcome to my App !")
})


//initialize port
let server = app.listen(PORT, function () {
    console.log(`Listening at http://localhost:${PORT}`);
});

export default server;

3 .Setup babel to compile es6

$ npm install @babel/core @babel/node @babel/preset-env

After that, we need to create a file called .babelrc at the root directory of our project and inside this file, we paste the block of code below.

{
   “presets”: [
     “@babel/preset-env”
   ]
}

Now, the setup is ready. we need to create a script to transpile our code on run time. To do this, edit the package.json file and add this:

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "babel lib -d dist",
    "start": "npm run build && nodemon dist/index.js",
    "serve": "node dist/index.js"
  },

Now we can use npm run build for precompiling our assets, and npm run serve for starting our server in production.

$ npm run build
$ npm run serve

This means we can quickly restart our server without waiting for babel to recompile our files.

Oh, let’s not forget to add dist to our .gitignore file:

$ touch .gitignore > dist

This will make sure we don’t accidentally commit our built files to git.

Testing the server
Finally let’s make sure our server is well tested.

4. Let’s install mocha and chai for unit testing.

$ npm install --save-dev mocha

And create our test in test/index.js.

$ mkdir test
$ touch test/index.js

and our test :

import assert from 'assert';
import http from 'http';
import server from '../lib/index';


describe('Server should be running at PORT 3000', () => {
  it('should return 200', done => {
    http.get('http://localhost:3000', res => {
      assert.equal(200, res.statusCode);
      server.close();
      done();
    });
  });
});

Next, install @babel/register for the require hook.

$ npm install --save-dev @babel/register


Then we can add an npm test script.

  "scripts": {
    "start": "nodemon lib/index.js --exec babel-node",
    "build": "babel lib -d dist",
    "serve": "node dist/index.js",
+   "test": "mocha --require @babel/polyfill --require @babel/register './tests/**/*.spec.js'"
  }

Now let’s run our tests.

$ npm test

You should see the following:

Server running at http://127.0.0.1:3000/

Example Node Server
✓ should return 200

1 passing (43ms)

5 .Adding Typescript

Let’s add two libraries to the development server as devDependencies.

typescript is a core library that helps to compile the TypeScript code to valid JavaScript
ts-node is a utility library that helps to run a development server written using TypeScript directly from the terminal

To install them, from a terminal window run the following command:

$ npm i -g typescript eslint ts-node
$ npm install --save-dev typescript ts-node 

We can test typescript using the following :

$ tsc filename.ts

We also need to Install types for all the packages

$ npm i --save-dev @types/body-parser @types/express @types/node @types/mongoose

tsconfig.json file :

{
    "compilerOptions": {
        "outDir": "./dist",
        "moduleResolution": "node",
        "module": "commonjs",
        "allowJs": true,
        "target": "es6"
    },
    "include": [
        "./src/**/*",
        "index.ts"
    ]
}

We would need :

$ npm install --save-dev @babel/plugin-transform-runtime @babel/preset-typescript tslint tslib typescript

let’s create our tslint.json to handle typechecking

{
    "defaultSeverity": "error",
    "extends": [
        "tslint:recommended"
    ],
    "jsRules": {},
    "rules": {
        "trailing-comma": [ false ]
    },
    "rulesDirectory": []
}

also, we need to modify our .babelrc file to this :

{
    "presets": [
        [
            "@babel/preset-env",
            {
                "targets": {
                    "node": "current"
                }
            }
        ], "@babel/preset-typescript"
    ],
    "plugins": ["@babel/plugin-transform-runtime"]
}

package.json

"scripts" : {
"build": "tsc --w",
"start": "tsc && ts-node ./dist/index.js"
}

our final package.json should be like this for both babel and typescript

  {
  "main": "dist/index.js",
  "scripts": {
    "test": "mocha --require @babel/register './tests/**/*.spec.js'",
    "prebuild": "tslint -c tslint.json -p tsconfig.json --fix",
    "dev-ts": "tsc --w",
    "build-ts": "npm run prebuild && tsc",
    "start-ts": "npm run build-ts && nodemon src/index.ts",
    "serve-ts": "npm run build-ts && ts-node ./dist/index.js",
    "build-js": "babel src -d dist",
    "start-js": "nodemon src/index.js --exec babel-node",
    "serve-js": "npm run build && node dist/index.js"
  },
}

Run the app:

$ npm start-ts

Now every time, the app is started tsc first converts typescript code in javascript and then ts-node runs the build js file. Your app should be running now, at http://localhost:3000

You can checkout this Github Repo, if you get stuck

Scroll to Top