Setup Code Linting in VSCode for Express Typescript Server with Eslint

  1. Setting up Nodejs Express Typescript Server
  2. Setting up a custom logger for node express typescript server
  3. Setup Code Linting in VSCode for Express Typescript Server with Eslint
  4. Configuring Tooling using ESLint, Editorconfig, Prettier and Husky
  5. Setting up React Client from scratch
  6. Configuring Monorepo with yarn workspaces and lerna
  7. Creating REST APIs using Node, Express, Typescript, Mongodb
  8. Configuring Typescript with React

Configuring ESlint for our Express Typescript Project with VScode

When setting up eslint for a project we usually have 3 options (choose any one ):

1. Install Eslint globally

We will install eslint dependency globally (means it will be available for all projects on your machine, cool!)

using npm

npm install -g eslint

using yarn

yarn global add eslint

Run eslint

eslint --init

2. Install Eslint for a project-only

We will install dependencies per-project, which can be useful to explicitly tell a developer to use these.

Go to the root of the project (where package.json lives)

cd my-project

using npm

npm install -D eslint

using yarn

yarn add -D eslint

Run eslint

eslint --init

3. Using npx (Recommended) We will use this !

npx eslint --init

This starts a interactive script to create a eslintrc.json, follow this steps

√ How would you like to use ESLint? · style
√ Which framework does your project use? · none
√ Does your project use TypeScript? · Yes
√ Where does your code run? · browser
√ How would you like to define a style for your project? · guide
√ Which style guide do you want to follow? · airbnb
√ What format do you want your config file to be in? · JSON
Checking peerDependencies of [email protected]
Local ESLint installation not found.
The config that you’ve selected requires the following dependencies:

@typescript-eslint/[email protected] [email protected] [email protected]^5.16.0 || ^6.8.0 || ^7.2.0 [email protected]^2.22.1 @typescript-eslint/[email protected]

√ Would you like to install them now with npm? · No

Installing @typescript-eslint/[email protected], [email protected], [email protected]^5.16.0 || ^6.8.0 || ^7.2.0, [email protected]^2.22.1, @typescript-eslint/[email protected]

This will create a eslintrc.json :

This will

{
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": [
        "airbnb-base"
    ],
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
        "ecmaVersion": 12,
        "sourceType": "module"
    },
    "plugins": [
        "@typescript-eslint"
    ],
    "rules": {
    }
}

If No, we have to install dependencies manually As it says, we need the following dependencies:

@typescript-eslint/[email protected] [email protected] [email protected]^5.16.0 || ^6.8.0 || ^7.2.0 [email protected]^2.22.1 @typescript-eslint/[email protected]

Let’s install the dependencies:

yarn add -D @typescript-eslint/[email protected] [email protected] eslint eslint-plugin-import @typescript-eslint/parser

Migrating from Tslint to Eslint

As we know Tslint is deprecated, its recommended to switch to Eslint, we gonna be using a tool for migrating.

You can find more info on the tool here Tslint to ESlint Config

If you have a tsconfig.json, which looks something similar:

{
    "compilerOptions": {
        "allowJs": true,
        "lib": ["es2016","esnext.asynciterable"], /* Libraries to be included in the compilation */
        "types": ["node"], /* list of names to contain type definitions */
        "target": "es2016", /* ECMASCript version of the target */
        "module": "commonjs", /* specify module code generation */
        "moduleResolution": "node", /* How to interpret the module */
        "outDir": "./dist", /* output directory */
        "strict": true, /* enable strict type checking option */
        "emitDecoratorMetadata": true, /* Send design-type metadata for decorator declaration to source */
        "experimentalDecorators": true, /* enabled for ES decorators */
        "sourceMap": true, /* Use Source Map */
        "allowSyntheticDefaultImports": true, /* Allow default imports from modules without default export */
        "esModuleInterop": true, /*'require' and'import' compatible */
        "skipLibCheck": true, /* Omit type checking of all declaration files (*.d.ts) */
        "resolveJsonModule": true, /* Include modules imported with .json extension */
    },
    "include": [
        "./src/**/*",
        "index.ts"
    ]
    "exclude": [
        "node_modules",
        "src/test",
        "**/*.spec.ts",
        "**/*.test.ts",
    ]
}

Run the following command to start migrating our tslint configuration to eslint :

npx tslint-to-eslint-config

This will start a interactive script to start the migration process:

It generates a huge, .eslintrc.js file based on existing tsconfig.json, with all the required settings for linting a typescript and javascript project,also will let you know if any other packages are required to be installed

a starter .eslintrc.js looks like this:

module.exports = {
  root: true,
  parser: '@typescript-eslint/parser',
  plugins: [
    '@typescript-eslint',
  ],
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
  ],
};

explaining a bit:

parser: ‘@typescript-eslint/parser’ tells ESLint to use the parser package you installed (@typescript-eslint/parser).
This allows ESLint to understand TypeScript syntax.
This is required, or else ESLint will throw errors as it tries to parse TypeScript code as if it were regular JavaScript.

plugins: [‘@typescript-eslint’] tells ESLint to load the plugin package you installed (@typescript-eslint/eslint-plugin).
This allows you to use the rules within your codebase.

extends: [ … ] tells ESLint that your config extends the given configurations.

eslint:recommended is ESLint’s inbuilt “recommended” config – it turns on a small, sensible set of rules which lint for well-known best-practices.

plugin:@typescript-eslint/recommended is our “recommended” config – it’s just like eslint:recommended, except it only turns on rules from our TypeScript-specific plugin.

In .eslintrc.js we need to change the project option in parser from tsconfig.json to .eslintrc.js. (otherwise Eslint will throw error)

{
 "parser": "@typescript-eslint/parser",
 "parserOptions": {
 "project": ".eslintrc.js",
 "sourceType": "module"
 },
}

As you see, the last script also said that, 5 packages are required for the new config, Let’s install them:

yarn add @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint eslint-plugin-jsdoc eslint-plugin-prefer-arrow --dev

Telling Vscode to use our .eslintrc.js for linting

First of all, we need to “teach” our editor to understand eslint 😄 So we’ll install this extension – https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint

After installation, we need to explicitly tell eslint extension to watch typescript files for linting errors (by default it lints only javascript and JSX files). Follow these instructions:

Inside VS Code use: Ctrl+Shift+P or Shift+Cmd+P
Type: Preferences: Open Settings (JSON)
Select the option
Paste this code inside the opened JSON file

{
  "eslint.options": {
        "configFile": "./.eslintrc.js"
   },
  "eslint.validate": ["typescript", "typescriptreact"],
}

Note that if you hit Ctrl+Shift+P or Shift+Cmd+P in VS Code and type eslint it will show you all commands available for this extensions!

Adding automatic lint errors fixing!

Cool, now editor shows error when we type something that violates our eslint rules and we can manually fix them, but that’s time-consuming, we can do better with automatic fixing!

All we need to do is to tell our VS Code eslint extension to run eslint –fix command on file save.

Inside VS Code use: Ctrl+Shift+P or Shift+Cmd+P
Type: Preferences: Open Settings (JSON)
Select the option
Update eslint-related code inside the opened JSON file

{
  "eslint.validate": [
    {
      "language": "typescript",
      "autoFix": true
    },
    {
      "language": "typescriptreact",
      "autoFix": true
    }
  ],
  "eslint.autoFixOnSave": true
}

Now whenever you save typescript file with eslint errors, it will be automatically fixed. Awesome!

Test Linting

Let’s add our lint command in package.json, –ext defines extentions, usually eslint command tests for javascript files to tell it to check typescript files we have added .ts, src/* is for telling eslint to only lint in the src directory of the project.

Scans from the root of the project

eslint --ext ts,tsx .

Scans only src directory of the project

eslint --ext ts,tsx src/*

Add this in our package.json :

{
 "scripts":{
     "lint": "eslint . --ext .ts src/*"
  }
}

Now let’s test for errors, run :

yarn lint

This will show all the errors in our code in the terminal, like this:

✖ 467 problems (465 errors, 2 warnings)
  309 errors and 0 warnings potentially fixable with the `--fix` option.

Ignore linting using .eslintignore

We also need to create a .eslintignore file to prevent linting particular folders and files.

# don't ever lint node_modules
node_modules
# don't lint build output (make sure it's set to your correct build folder name)
dist
# don't lint nyc coverage output
coverage

Replacing ts-node with ts-node-dev

Also, let’s switch to ts-node-dev, since it is similar to ts-node, so that .ts can be executed immediately without compiling the JavaScript file. In addition, when the file is changed, it helps to re-execute and debug through inspect.

Install ts-node-dev.

yarn add -D ts-node-dev

Now you can add a command for running dev in package.json scripts:

"scripts:{
   "dev": "ts-node-dev --inspect --watch -- ./src/index.ts",
}

Run :

yarn dev

This will help us in debugging process alot !

Setting up Debugger in vscode

If there is no .vscode folder, create a folder and enter ./.vscode/launch.json file as below.

{
    "version": "0.2.0",
    "configurations": [
      {
        "type": "node",
        "request": "launch",
        "name": "Launch via Yarn",
        "runtimeExecutable": "yarn",
        "program": "${workspaceFolder}/src/index.ts",
        "runtimeArgs": [
          "start:debug"
        ],
        "env": {
          "SRC_PATH": "dist/"
        },
        "sourceMaps": true,
        "smartStep": true,
        "internalConsoleOptions": "openOnSessionStart",
        "outFiles": [
          "${workspaceFolder}/dist/**/*.js"
        ],
        "port": 5858,
        "timeout": 10000
      },
      {
        "type": "node",
        "request": "attach",
        "name": "Attach to Inspector",
        "protocol": "inspector",
        "port": 9229,
        "cwd": "${workspaceRoot}"
      }
    ]
  }

We also need to add the following script in package.json :

{
 "scripts:  {
    "dev-ts": "ts-node-dev --inspect --watch -- ./src/index.ts",
    "start:debug": "node --inspect-brk=5858 ./dist/index.js",
  }
}

How to launch debugger?

So we have added two configurations in our launch.json , the first one is for “Launch via Yarn” which triggers the start:debug command and also starts the debugger in vscode.
the second one “Attach to Inspector” attaches any terminal running with the dev-ts command to the vs-code debugger.

You will be able to find a debug icon in side drawer in vs-code, once you click it. you will see a sidebar where you can see all your breakpoints(the red dots).

Now click in front of the row where you want to breakpoint or press the F9 key and you will see a red circle in front of the row.

Running Launch via Yarn

Select the debug menu on the left or press the Ctrl+Shift+D key to move to the debug menu, select Launch via Yarn and press the F5 button. You can check the status of debugger. You can now be able to debug the application in Vscode.

Running Attach Inspector

You need to use a terminal and run yarn dev-ts this will start the server in watch mode and a Debugger listening. Alternatively, after running the program with yarn dev in the terminal, select Attach to Inspector from the debug menu and press F5 to debug from the middle without running it individually.

run – yarn dev
server restarts on changes..

Remove TSLint

Optional Removing Tslint, we will be using eslint from now onwards so.

yarn remove tslint

also remove tslint.json, which contained this:

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

and remove script for prebuild from package.json. Since we won’t be using Tslint (its deprecated), but to know how to use it.

Scroll to Top