Setting up a NodeJs server with Typescript

Setting up a NodeJs server with Typescript

A beginner's guide to set up a Node Server with TypeScript, Eslint, and Prettier.

If you have arrived here in search of TypeScript setup for your nodejs project, this comprehensive guide should help you get started on your journey to building robust and maintainable Node.js applications with TypeScript.

Step 0: Installing NodeJS

Download or upgrade to the latest version of Node.

Step 1: Initialize Your Project

To get started, create a new Node.js project by running the following command:

yarn init -y

This command generates a package.json file with default settings.

{
  "name": "nodejs-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
}

We will make some adjustments to it later.

Step 2: Use CommonJS Modules

CommonJS and ES modules are two different ways of importing and exporting modules in JavaScript. CommonJS, historically used in Node.js, relies on the require function for importing modules and module.exports for exporting them. In contrast, ES modules, introduced in ES6, use import and export statements. This distinction impacts how code is structured and dependencies are handled in their respective environments. CommonJS has been the standard in Node.js for a long time, while ES modules (ECMAScript modules) offer native support for modules in JavaScript.

Since we are using TypeScript, which compiles to CommonJS by default, we do not need to enable "type: module" in our package.json file. This allows us to continue using CommonJS syntax without changing the module system. The package.json file looks like this until now:

{
  "name": "nodejs-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
       "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
}

Step 3: Install TypeScript

Install TypeScript as a development dependency using the following command:

yarn add -D typescript

Step 4: Configure TypeScript

Create a tsconfig.json file to configure TypeScript. This file specifies how TypeScript should transpile your code. Here's a breakdown of the key options in the tsconfig.json file:

  • "type": "module": Specifies the module system used by Node.js.

  • "esModuleInterop": true: Enables compatibility between CommonJS and ES Modules.

  • "target": "es2021": Sets the ECMAScript version to target.

  • "moduleResolution": "node": Configures how TypeScript resolves module imports.

  • "sourceMap": true: Generates source maps for better debugging.

  • "outDir": "dist": Specifies the output directory for transpiled code.

  • "strict": true: Enforces strict type checking.

  • "include" and "exclude": Define which files to include and exclude from TypeScript compilation.

  • "lib": ["es2021"]: Specifies the libraries available in your TypeScript project.

Here's the tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es2021",
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "./dist",
    "strict": true,
    //"skipLibCheck": true,              
    //"noImplicitAny": true,  
    //"strictNullChecks": true,
    //"strictFunctionTypes": true,
    //"noImplicitReturns": true 
  },
  "include": ["src/**/*.ts", "index.ts"],
  "exclude": ["node_modules"],
  "lib": ["es2021"]
}

You can optionally create tsconfig.json using the command npx tsc --init which will create it with various options available and you can choose which to keep, like below:

Step 5: Install Express

You can use the popular Express.js framework to build your Node.js server. Install it using the following command:

yarn add express

Step 6: Create Your TypeScript Entry File

Create src directory and add an index.ts file it to serve as the entry point for your application:

import express from "express";

const app = express();
const port = 3000;

app.get("/", (req, res) => {
  res.send("Hello, TypeScript Node.js Server!");
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Step 7: Install @types/express and @types/node

Since TypeScript needs type definitions for external packages, importing express will give an error so install @types/express:

yarn add -D @types/express @types/node

This package provides TypeScript type declarations for Express.js.

Step 8: Setting Up Development Scripts

For a smoother development experience, install nodemon as a global package.

Nodemon is a utility for Node.js that automatically restarts the server when changes are detected in the code. It's commonly used during development to streamline the development process by eliminating the need to manually restart the server after every code change. This tool significantly enhances the development workflow, allowing developers to focus on writing code without the interruption of restarting the server repeatedly. You will also need to install ts-node which is a Typescript execution engine.

yarn add nodemon ts-node -g

Then, update your package.json file to include scripts for starting your server in development mode:

"scripts": {
  "dev": "nodemon src/index.ts"
}

Now, you can run your server with yarn dev and it will automatically restart when you make changes to your TypeScript code.

Let's also add scripts to build and start our application, yarn build will compile all your typescript files into javascript and store in the 'dist' directory as specified in the tsconfig.json.

"scripts": {
  "build": "tsc",
  "start": "node dist/index.js",
}

After the build is succeeded, you can run yarn start to start your application.

Step 9: Adding ESLint for Code Quality

ESLint is a popular static code analysis tool for identifying problematic patterns found in JavaScript code. It helps ensure that your code follows best practices, conforms to coding standards, and avoids common errors.

Developers use ESLint to enforce coding styles and conventions within a project, making the codebase more consistent and readable. It can catch bugs, potential runtime errors, and even detect suspicious code that might lead to unexpected behaviors. Additionally, ESLint can be customized with various plugins and configurations to suit the specific needs and preferences of a project or development team.

Install ESLint and TypeScript-specific ESLint packages:

yarn add -D eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser

Create an .eslintrc.json file in your project directory:

{
  "env": {
    "node": true,
    "es2021": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": 2021,
    "sourceType": "module"
  },
  "plugins": [
    "@typescript-eslint"
  ],
  "rules": {}
}

Add a lint script in the package.json,

"scripts": {
    "lint": "eslint index.ts && eslint src/**/*.ts",
}

Step 10: Adding Prettier for Code Formatting

Prettier is a code formatting tool that automatically adjusts the layout and style of your code to follow a consistent and predefined set of rules. It helps maintain a uniform code style across a project by automatically formatting the code according to the configured guidelines. Prettier is commonly used in development environments to ensure that code is easy to read, consistent, and visually appealing, which in turn enhances collaboration and maintains a clean codebase.

Install it:

yarn add -D prettier

Create a .prettierrc file in your project directory with your preferred formatting rules:

{
  "semi": true,
  "trailingComma": "all",
  "singleQuote": true,
  "printWidth": 120,
  "tabWidth": 2
}

Add a script to format your code:

"pretty": "prettier --write \"src/**/*.ts\""

Now, you can run yarn pretty to format your TypeScript files in the src directory of your project.

To build and start your application run yarn build and yarn start.

Congratulations! You've successfully set up a Node.js server with TypeScript, added linting with ESLint, code formatting with Prettier. Happy coding!