In this blog, we will discuss Node.js with typescript. Basically, we will learn the demonstration on how to create a project with the mentioned frameworks and programming language. Before proceeding you should ensure that you have a basic knowledge of TypeScript, Node.js, and Express. Also, you are using or plans to use, Node.js version 12 or greater.

Node.js with typescript

Also Read: Node js on docker: Everything you need to know

1. Set up the project

Firstly, you should create a directory for the project and initialize it. Then, run the following commands in order to create an empty directory called typescript-nodejs. You have to change the current directory to it.

mkdir typescript-nodejs
cd typescript-nodejs

Now you have to initialize our Node project from the typescript-nodejs directory. Run the following command in order to do so:

npm init -y

When you use the -y flag in the above command then it generates the package.json file with the default values. npm initializes the file with default values that can be updated later instead of adding information ourselves. For instance, the name and description of the project. After initializing the project, we can add the required dependencies now.

2. Add dependencies

You need to add TypeScript and the Express framework. Run the following commands in order to do so:

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

When you install TypeScript-related dependencies then, it will be installed as devDependencies. The reason for this is even though code is written in TypeScript, it will be compiled as “vanilla” JavaScript. The only use for TypeScript is during development and not for runtime. It will be installed as a dev dependency since TypeScript has developer as its only “consumer”.

After the dependency installations are complete, your package.json will look as follows:

{
  "name": "typescript-nodejs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "@types/express": "^4.17.9",
    "@types/node": "^14.14.20",
    "ts-node": "^9.1.1",
    "typescript": "^4.1.3"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

3. Configure TypeScript

The installation of TypeScript is complete but still you cannot use it yet. This is because you should configure it first. For this, you have to create a file by the name of tsconfig.json. This will indicate that the directory is the root of a TypeScript or JavaScript project.

npx tsc --init

When you run the above command then it will create the tsconfig.json file where you can customize the TypeScript configuration. The creation of a new file will be containing a lot of code, most of it is comment out. There are some important settings that you must know:

  • target: With the help of this option, you can specify which ECMAScript version to use in your project. Let’s give you an example, if you set the target to ES5 and then you use arrow functions. The code will get compilation to an equivalent ES5 function. Some of the available versions are ES3 (default), ES5ES2015ES2016ES2017ES2018ES2019ES2020, or ESNEXT.
  • module: Using this option, you will be able to specify which module manager to use after the generation of JavaScript code. You have the option to choose between the following values nonecommonjsamdsystemumdes2015es2020, or ESNext. The deafult and most common module is commonjs.
  • rootDir: This option specifies the location of the TypeScript files.
  • outDir: Using this option, you will be able to specify where to output the “vanilla” JavaScript code.
  • esModuleInterop: This option by default is true. It has the ability to control interoperability between CommonJS and ES modules. It can do this by creating namespace objects for all imports.
  • strict: This option is enabled by default. And it toggles strict type-checking options.

4. Create an Express server

Now we are all done with Typescript so we can create the Express web server. For that, we must create the index.ts (attention to the file extension) by running touch index.ts.

import express from 'express';

const app = express();

app.get('/', (req, res) => {
    res.send('Well done!');
})

app.listen(3000, () => {
    console.log('The application is listening on port 3000!');
})

A simple web server will show you “Well done!” after you access localhost:3000 a browser. The server is very simple and doesn’t take advantage of TypeScript at least not yet. But the reason for this blog is to make Node.js, TypeScript, and Express work together and create a boilerplate. The application will be customized from there.

When you want to run the application after making changes, you have to compile TypeScript to “vanilla” JavaScript. Run the following command in order to do so:

npx tsc --project ./

You can compile TypeScript to JavaScript by using the command tsc. The flag --project specifies from where you can pick the TS files. And last but not least,  ./ specifies the root of the project.

You will see the compilation of JavaScript code when you access the build folder. This is the compilation of code from the TypeScript code you wrote.

5. Create scripts

It will be difficult for you to write npx tsc --project ./ every time during the compilation of the code. In order to automate this, you can add a script to package.json that will take care of it.

You just have to add the following line of code in package.json under scripts in order to automate compiling the TypeScript code to JavaScript:

"build": "tsc --project ./"

Now for the compilation of the code, you can run npm run build. It will make your task easier and simpler.

Conclusion

By using this method you can easily use Node.js with typescript. Also, this what we explained is only tip of the iceberg and you can easily build any application you want from here. Hope you find this information useful. Thank you for the read.

Categorized in:

Tagged in: