Scaffolding Nodejs Typescript Project

Node.js is an asynchronous event driven Javascript runtime that enables the development of scalable network applications.

NodeJS

NodeJS Typescript Scaffolding

Node.js is an asynchronous event-driven Javascript runtime that enables the development of scalable network applications. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient for developing data-intensive applications.

Typescript is the strictly syntactical superset of Javascript. Nodejs engine runs Javascript so typescript needs to be transpiled to javascript in order to run on NodeJS.For a large JavaScript project adopting Typescript can bring you more robust software and easily deployable with a regular JavaScript application.

In this article, we will explore how a nodejs typescript project can be scaffolded.

Create Project
npm init command can be used to setup a new or existing npm package. Here that package will be the new project in our case.

npm init

Install express and body-parser

npm i express body-parser --save

Install Typescript package

npm i typescript --save

It will install typescript for our project and update the package.json.

After we have installed typescript we have to create tsconfig.json, which will be used by compiler to transpile the typescript file and other compiler options. It can be created using

npx tsc --init

Update your tsconfig.json as follows

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "noImplicitAny": true,
        "moduleResolution": "node",
        "sourceMap": true,
        "outDir": "dist",
        "baseUrl": ".",
        "paths": {
            "*": [
                "node_modules/*"
            ]
        },
        "resolveJsonModule": true,
        "esModuleInterop": true
    },
    "include": [
        "./**/*"
    ]
}

After we have setup the typescript we should add typed packages for express.

npm i @types/express @types/body-parser --save-dev

Now we are all set to start writing code for our scaffolding project

Create an index.ts and app.ts file

import * as http from "http";
import app from "./app";

http.createServer(app).listen(9000, () => {
        // tslint:disable-next-line:no-console
console.log("Server started");
});
import * as bodyParser from "body-parser";
import express from "express";
import { Routes } from "./routes/routes";

class App {
    public app: express.Application;
    public routes = new Routes();

    constructor() {
        this.config();
        this.routes.routes(this.app);
    }
    public config(): void {

        this.app = express();
        this.app.use(bodyParser.json());

        this.app.use(bodyParser.urlencoded({ extended: false }));

        this.app.use((req: express.Request, res: express.Response, next: express.NextFunction): any => {

            return next();
        });

        this.app.use(express.static("public"));
    }
}
export default new App().app;

Create routes.ts in routes/routes.ts

import { NextFunction, Request, Response } from "express";

export class Routes {
    public routes(app: any): void {
        app.route("/").get((req: Request, res: Response, next: NextFunction) => {
            res.status(200).send({ message: "Done" });
        });
    }}

In package.json update scripts to

"scripts":{"build": "tsc"}

Compile the code now using

npm run build

Transpiled code or javascript build will be available in dist folder. Run the app using

node dist/index.js

You can also download the code from github.