Setting up a TypeScript Express Server with Prettier and ESLint

Setting up a TypeScript Express Server with Prettier and ESLint

Here is a quick tutorial on how to set up a TypeScript express server with ESLint and Prettier.

Prerequisites

Please make sure you have the following installed in your local development environment:

  • Node.js version >= 14.x.x installed
  • Access to one package manager such as npm or yarn

1. Creating project directory

Create a project folder and use npm’s initializer command to create a package.json file:

$ mkdir server
$ cd server
$ npm init --yes

The --yes flag uses the default settings when initializing a package.json from the npm config you might have set up.

The package.json file created might look something like this:

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

2. Adding packages and config

We'll start by adding the following packages-

Dependencies:

  • express: Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications APIs.

  • dotenv: It is a lightweight npm package that automatically loads environment variables from a . env file into the process. env object.

Dev Dependencies

  • typescript: Helps us write code in typescript and compile all of our codebases into plain javascript.

  • ts-node: It helps us to run typescript code without precompiling to JS for faster development.

  • nodemon: It is a simple monitor script for use during the development of a node.js app. It allows us to automatically restart the server when we make any changes in our code.

  • @types/express : This package contains type definitions for Express

We'll install more packages later but let's start with the above ones-

$ npm install express
$ npm install dotenv
$ npm install -D typescript
$ npm install -D ts-node
$ npm install -D nodemon
$ npm install -D @types/express

Setting up TSConfig

The presence of a tsconfig.json file in a directory indicates that the directory is the root of a TypeScript project. The tsconfig.json file specifies the root files and the compiler options required to compile the project.

Run the following command at the root of your project directory-

$ tsc --init

This command will generate a tsconfig.json file at the root of your project directory. The JSON will have many fields with comments explaining what they are and what are the possible values for each field.

Please make sure you have the following fields uncommented out with the following values-

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "lib": ["es6", "dom"],
    "sourceMap": true,
    "outDir": "dist",
    "rootDir": "src",
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}

You can learn more about these options here

Setting up ESLint + Prettier for linting and code formatting-

Installing ESLint:

$ npm install -D eslint
$ npm install -D @typescript-eslint/parser
$ npm install -D @typescript-eslint/eslint-plugin
$ npm install -D eslint-config-airbnb-base
$ npm install -D eslint-plugin-import

Installing Prettier:

$ npm install -D prettier
$ npm install -D  eslint-config-prettier
$ npm install -D eslint-plugin-prettier

Create a .prettierrc.yml file in your project directory-

tabWidth: 2
singleQuote: true

Next, create a .eslintrc.yml configuration file in your root folder to setup rules and parsing for the project-

env:
  es2021: true
  node: true
extends:
  - airbnb-base
  - plugin:@typescript-eslint/recommended
  - plugin:prettier/recommended
  - plugin:import/recommended
  - plugin:import/typescript
parser: '@typescript-eslint/parser'
parserOptions:
  ecmaVersion: 12
  sourceType: module
  project: ./tsconfig.json
plugins:
  - '@typescript-eslint'
rules:
  no-console: 'off'
  import/extensions: 'never'

Note that I have also addeded congigurations to integrate Prettier with ESLint, in the .eslintrc.yaml

Now, let's create a folder src and a file index.ts-

$ mkdir src
$ cd src
$ touch index.ts

Let's also add the following code, to begin with a minimal express server-

import express from 'express';
const app = express();
const PORT = 4000;

app.get('/', (req, res) => res.send('Express + TypeScript Server'));
app.listen(PORT, () => {
  console.log(`⚡️[server]: Server is running at https://localhost:${PORT}`);
});

Adding a Start Script:

Now, let's add some scripts to make it easier to run our code. Add the following to the package.json file.

  "scripts": {
    "start": "node dist/index.js",
    "build": "tsc",
    "dev": "nodemon --watch 'src/**/*.ts' --exec 'ts-node' src/index.ts",
    "lint": "eslint .",
    "lint:fix": "eslint . --fix"
  }

Now you should be able to start the server using the command npm run dev and test it in your browser.

Visiting http://localhost:4000 in your browser should display Express + TypeScript Server text.

Extra: VS code settings I have installed some extensions and added the following setting to enable auto formatting on save etc-

Add a file .vscode/setting.json at the root of your project directory-

{
  "editor.tabSize": 2,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "editor.formatOnPaste": true,
  "editor.formatOnType": true,
  "eslint.alwaysShowStatus": true,
  "files.autoSave": "onFocusChange",
  "[javascript]": {
    "editor.formatOnSave": false
  }
}

You'll also need to install the following extension-

Credits