How To Set Up a Node Project With Typescript

PostedDecember 12, 2019 21.5k views Node.js

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

Node is a run-time environment that makes it possible to write server-side JavaScript. It has gained widespread adoption since its release in 2011. Writing server-side JavaScript can be challenging as a codebase grows due to the nature of the JavaScript language; dynamic and weak typed.

Developers coming to JavaScript from other languages often complain about its lack of strong static typing; this is where TypeScript comes into the picture, to bridge this gap.

TypeScript is a typed (optional) super-set of JavaScript that can help with building and managing large-scale JavaScript projects. It can be thought of as JavaScript with additional features like strong static typing, compilation and object oriented programming.

Note: TypeScript is technically a super-set of JavaScript, which means that all JavaScript code is valid TypeScript code.

Here are some benefits of using TypeScript:

  1. Optional static typing.
  2. Type inference.
  3. Ability to use Interfaces.

This tutorial will teach you to set up a Node project with TypeScript. You will build an Express application using TypeScript and transpile it down to neat, reliable JavaScript code.

Prerequisites

In this section, we will go over the setup and configuration required to enable our computer to run a Node application using TypeScript. If you already have Node installed you can skip to the next section.

Installing Node

Let’s begin by installing the Node run-time on our machine. If you are on a Debian or Ubuntu distro of Linux, open a terminal and run the following commands:

  • curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
  • sudo apt-get install -y nodejs

You will need curl installed on your machine to run the first command. Curl is a command-line tool for transferring data using various protocols.

If you are on a different operating system, visit https://nodejs.org/en/download/ for Node installation instructions.

Once the installation is complete, confirm that it was successful by checking the Node and NPM versions installed:

  • node -v
  • npm -v

At the time of writing this article, the stable versions for Node and Npm are 10.15.1 and 6.7.0 respectively.

Initializing an Npm project

Now that Node and Npm are installed, create a new folder and initialize it as an Npm project:

  • mkdir node_project
  • cd node_project
  • npm init

Note: After running npm init, you will need to supply Npm with information about your project. If you’d rather let Npm guess sensible defaults then you can add the y flag and you will not be prompted to add any additional information: npm init -y

Installing Dependencies

So far you have installed Node and initialized a bare Npm project. The next step is to install the dependencies that are required to runTypescript. Navigate into the project directory that you just created and run the following commands:

  • npm install -D typescript
  • npm install -D tslint

The -D flag is the shortcut for: --save-dev. You can learn more about this flag in the npmjs documentation.

Now it is time to install the Express framework:

  • npm install express -S
  • npm install @types/express -D

The second command above installs the Express types for TypeScript support. This package is required because TypeScript and Express are independent packages. Without the @types/express package, there is no way for TypeScript to know about the types of Express classes.

Note: Types in TypeScript are files, normally with an extension of .d.ts*. The files are used to provide type information about an API, in this case the Express framework.

Configuring TypeScript

In this section, you will setup TypeScript and configure linting for TypeScript. TypeScript uses a file called tsconfig.json to configure the compiler options for a project. Create a tsconfig.json file in the root of the project directory and paste in the following snippet:

{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist"
  },
  "lib": ["es2015"]
}

Let’s go over some of the keys in the JSON snippet above and see what they do:

  • module : Specifies the module code generation method. Node uses commonjs.
  • target: Specifies the output language level.
  • moduleResolution: This helps the compiler figure out what an import refers to. The Valuenode mimics the Node module resolution mechanism.
  • outDir: This is the location to output .js files after transpilation. We save it as dist.

An alternative to manually creating and populating the tsconfig.json file is running: tsc --init. This command will generate a nicely commented tsconfig.json file.

To learn more about the key value options available, the official TypeScript documentation offers explanations of every option.

Now you can configure TypeScript linting for the project. In a terminal running in the root of your project’s directory, run the following command to generate a tslint.json file:

  • ./node_modules/.bin/tslint --init

Open the newly generated tslint.json file and add the no-console rule accordingly:

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

By default, the Typescript linter prevents the use of debugging using console statements, hence the need to explicitly tell the linter to revoke the default no-console rule.

Updating the Package.json file

At this point in the tutorial, you can either run functions in the terminal individually, or create an ’npm script’ to run them. In this step you will make a start script that will compile and transpile the TypeScript code, and then runs the resulting .js application.

Open the package.json file and update it accordingly:

{
  "name": "node-with-ts",
  "version": "1.0.0",
  "description": "",
  "main": "dist/app.js",
  "scripts": {
    "start": "tsc && node dist/app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/express": "^4.16.1",
    "tslint": "^5.12.1",
    "typescript": "^3.3.3"
  },
  "dependencies": {
    "express": "^4.16.4"
  }
}

In the snippet above, you updated the main path and added the start command to the scripts section. Taking a close look at the start command, first the tsc command is run, and then the node command. This will compile and then run the generated output with node.

NOTE: The tsc command tells TypeScript to compile the application and place the generated .js output in the specified outDir directory as it is set in the tsconfig.json file.

Setting Up The Folder Structure

Now create a src folder in the root of our project directory and then create a file called app.ts within it:

  • mkdir src
  • cd src
  • touch app.ts

At this point, the folder structure should look like this:

├── node_modules/
├── src/
  ├── app.ts
├── package-lock.json
├── package.json
├── tsconfig.json
├── tslint.json

Creating and Running a Basic Express Server

Now that TypeScript and its linter are configured, it is time to build a Node Express Server. Open up the app.ts file and paste in the following code snippet:

import express from 'express';

const app = express();
const port = 3000;
app.get('/', (req, res) => {
  res.send('The sedulous hyena ate the antelope!');
});
app.listen(port, err => {
  if (err) {
    return console.error(err);
  }
  return console.log(`server is listening on ${port}`);
});

The code above creates Node Server that listens on the port 3000 for requests. Run the app using the following command:

  • npm start

If it runs successfully, a message will be logged to the terminal server is listening on 3000. Now you can visit http://localhost:3000 in your browser and you should see the message: “The sedulous hyena ate the antelope!”

Open the dist/app.js file and you will find the transpiled version of the TypeScript code:

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const app = express_1.default();
const port = 3000;
app.get('/', (req, res) => {
    res.send('The sedulous hyena ate the antelope!');
});
app.listen(port, err => {
    if (err) {
        return console.error(err);
    }
    return console.log(`server is listening on ${port}`);
});

//# sourceMappingURL=app.js.map

At this point you have successsfully set up your Node project to use TypeScript.

Conclusion

In this tutorial, you learned about why TypeScript is useful for writing reliable JavaScript code. You also learned about some of benefits to working with TypeScript.

Finally, you set up a Node project using the Express framework, but compiled and ran the project using TypeScript.

Creative Commons License