Creating a Node.js project with Typescript

Introduction

In this tutorial module, you will create a TypeScript Node project. You will use TypeScript to construct an Express application that will be converted into clean and robust JavaScript code.

Node is a framework for writing server-side JavaScript programs. Since its initial release in 2011, it has grown in popularity. Writing JavaScript server code as the code base increases can be difficult due to the nature of JavaScript: dynamic and poorly typed.

Developers who transition to JavaScript from other languages frequently grumble about the absence of powerful static typing, however, TypeScript eliminates this limitation.

TypeScript is a generic (optional) JavaScript superset that can aid in the development and management of big JavaScript projects. It is similar to JavaScript, but with extra features like as powerful static typing, compilation, and object-oriented programming.

 

Necessary requirements

You must first install Node.js on your PC before proceeding with this module. You can accomplish this by following the recommendations for installing Node.js and creating a local development environment for your operating system.

A Virtual machine – feel free to signup with Pilvio

 

Step 1: Launch the npm project.

First, make a new folder called node project and navigate to it.

mkdir node_project
cd node_project

Then start it as a npm project:

npm init

 

After running npm init, you must provide npm with project information. You can bypass the dialogs asking for more information if you enable npm to accept tangible defaults:

npm init-y

 

Our project space is now ready, and you can begin installing the required dependencies.

 

Step 2: Set up dependencies for Typersript (Node setup)

Following the initialization of the base npm project, the following step is to install the TypeScript dependencies.

To install dependencies, run the following commands from your project directory:

npm install -D typescript@3.3.3
npm install -D tslint@5.12.1

 

The -D flag stands for the option: —save-dev. This flag is covered in further detail in the npmjs manual.

It is now time to set up the Express platform:

npm install -S express@4.16.4
npm install -D @types/express@4.16.1

 

The second command adds Express types to the system to support TypeScript. Types in TypeScript are files that commonly end with .d.ts. The files provide API-type information, in this case for the Express structure.

Because TypeScript and Express are separate packages, this package is necessary. Express class types cannot be recognized without the @types/express package.

 

Step 3: TypeScript Configuration

Now we will configure TypeScript and TypeScript compliance checking. The tsconfig.json file is used by TypeScript to configure compiler parameters for the project. Create a tsconfig.json file in the project’s root directory and add the following code:

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

 

Consider the following keys from the JSON code snippet:

 

  • module: determines how module code is generated. Node employs commonjs.
  • target: specifies the language level of the output.
  • moduleResolution: This property assists the compiler in determining what the import refers to. The value of node emulates Node’s module resolution method.
  • outDir: This is where the.js files are saved after they have been translated. We’ll store it as dist in this tutorial.

 

You can use the following command instead of manually creating and filling up the tsconfig.json file:

tsc --init

 

This command creates a tsconfig.json file with the appropriate annotations.

To understand more about the available key-value possibilities, consult the TypeScript documentation, which includes descriptions for all of them.

For this project, you may now enable TypeScript code compliance verification. To generate the tslint.json file, open the terminal and navigate to your project’s root directory, which is set to node project in this tutorial module, and run the following command:

./node_modules/.bin/tslint --init

 

Add the necessary no-console rule to the resulting tslint.json file:

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

 

The TypeScript validation module by default limits the use of console commands for debugging, thus you must explicitly direct it to disable the default no-console rule.

 

Step 4: Update the package.json file.

You may now run the functions separately in the terminal or in a npm script.

In this phase, we’ll write a start script that compiles and translates the TypeScript code before running the resulting.js application.

 

Open the package.json file and make the following changes:


{
"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"
}
}

 

We modified the main path and added the start command to the scripts section in the above code snippet. When you run the start command, you’ll notice that the tsc command is executed first, followed by the node command. This will use node to compile and run the generated output.

The tsc command tells TypeScript to compile the application and save the generated.js output to the outDir directory given in the tsconfig.json file.

 

Step 5: Build and execute the basic Express Server.

We can begin developing the Node Express Server module now that TypeScript and the validation module have been configured.

 

First, establish a src folder in your project’s root directory:

mkdir sr

 

Then create a file named app.ts:

touch src/app.ts

 

The directory structure should now look like this.

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

 

In your favourite text editor, open the app.ts file and paste 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 preceding code creates a Node server that listens for requests on port 3000. Use the following command to start the application:

npm start

 

On successful execution, the following message will be displayed on the terminal:

Output
server is listening on 3000

The server is now listening on port 3000.

You can now use your browser to access http://localhost:3000 and view the following message:


Output
The sedulous hyena ate the antelope!

 

The browser window with the message: The sedulous hyena ate the antelope!

When you open the dist/app.js file, you’ll see a transliterated 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

 

You have successfully enabled TypeScript in your Node project.

 

Conclusion

You learnt why TypeScript is useful for building robust JavaScript code in this tutorial. You also learnt about some of the advantages of using TypeScript.

 

Finally, you created a Node project with the Express framework but compiled and executed it with TypeScript.

Share on facebook
Share on linkedin
Share on twitter
Share on pinterest
Share on email

Related News