Using ESLint and Prettier in a TypeScript Project

Banner Image.

When it comes to linting TypeScript code, there are two major linting options to choose from: TSLint and ESLint. TSLint is a linter than can only be used for TypeScript, while ESLint supports both JavaScript and TypeScript.

In the TypeScript 2019 Roadmap, the TypeScript core team explains that ESLint has a more performant architecture than TSLint and that they will only be focusing on ESLint when providing editor linting integration for TypeScript. For that reason, I would recommend using ESLint for linting TypeScript projects.


Setting up ESLint to work with TypeScript

First, install all the required dev dependencies:

yarn add eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin --dev
Note: If using create-react-app to bootstrap a project, eslint is already included as a dependency through react-scripts, and therefore it is not necessary to explicitly install it with yarn.

Next, add an .eslintrc.js configuration file in the root project directory. Here is a sample configuration for a TypeScript project:

module.exports = {
  parser: "@typescript-eslint/parser", // Specifies the ESLint parser
  extends: [
    "plugin:@typescript-eslint/recommended" // Uses the recommended rules from the @typescript-eslint/eslint-plugin
  ],
  parserOptions: {
    ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features
    sourceType: "module" // Allows for the use of imports
  },
  rules: {
    // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
    // e.g. "@typescript-eslint/explicit-function-return-type": "off",
  }
};
Note: I prefer using a JavaScript file for the .eslintrc file (instead of a JSON file) as it supports comments that can be used to better describe rules.

If using TypeScript with React, the eslint-plugin-react dev dependency should be installed and the following configuration can be used:

module.exports = {
  parser: "@typescript-eslint/parser", // Specifies the ESLint parser
  extends: [
    "plugin:react/recommended", // Uses the recommended rules from @eslint-plugin-react
    "plugin:@typescript-eslint/recommended" // Uses the recommended rules from @typescript-eslint/eslint-plugin
  ],
  parserOptions: {
    ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features
    sourceType: "module", // Allows for the use of imports
    ecmaFeatures: {
      jsx: true // Allows for the parsing of JSX
    }
  },
  rules: {
    // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
    // e.g. "@typescript-eslint/explicit-function-return-type": "off",
  },
  settings: {
    react: {
      version: "detect" // Tells eslint-plugin-react to automatically detect the version of React to use
    }
  }
};

Ultimately it's up to you to decide what rules you would like to extend from and which ones to use within the rules object in your .eslintrc.js file.

Adding Prettier to the mix

What works well along with ESLint is prettier, which does a great job at handling code formatting. Install the required dev dependencies to get prettier working with ESLint:

yarn add prettier eslint-config-prettier eslint-plugin-prettier --dev

In order to configure prettier, a .prettierrc.js file is required at the root project directory. Here is a sample .prettierrc.js file:

module.exports = {
  semi: true,
  trailingComma: "all",
  singleQuote: true,
  printWidth: 120,
  tabWidth: 4
};

Next, the .eslintrc.js file needs to be updated:

module.exports = {
  parser: "@typescript-eslint/parser", // Specifies the ESLint parser
  extends: [
    "plugin:react/recommended", // Uses the recommended rules from @eslint-plugin-react
    "plugin:@typescript-eslint/recommended", // Uses the recommended rules from the @typescript-eslint/eslint-plugin
    "prettier/@typescript-eslint", // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
    "plugin:prettier/recommended" // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
  ],
  parserOptions: {
    ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features
    sourceType: "module" // Allows for the use of imports
  }
};

The advantage of having prettier setup as an ESLint rule using eslint-plugin-prettier is that code can automatically be fixed using ESLint's --fix option.

Automatically Fix Code in VS Code

For a good developer experience, it's useful to setup your editor to automatically run ESLint's automatic fix command (i.e. eslint --fix) whenever a file is saved. Since i'm using VS Code, here is the config required in the settings.json file in VS Code to get automatic fixing whenever saving a file:

{
  // "eslint.autoFixOnSave": true, // has been deprecated, use editor.codeActionsOnSave instead
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    { "language": "typescript", "autoFix": true },
    { "language": "typescriptreact", "autoFix": true }
  ]
}

If you've also set the editor.formatOnSave option to true in your settings.json, you'll need to add the following config to prevent running 2 formatting commands on save for JavaScript and TypeScript files:

{
  "editor.formatOnSave": true,
  "[javascript]": {
    "editor.formatOnSave": false
  },
  "[javascriptreact]": {
    "editor.formatOnSave": false
  },
  "[typescript]": {
    "editor.formatOnSave": false
  },
  "[typescriptreact]": {
    "editor.formatOnSave": false
  }
}

Run ESLint with the CLI

A useful command to add to the package.json scripts is a lint command that will run the TypeScript compiler and the ESLint linter across all project files to make sure the code adheres to the compiler settings and formatting/style rules.

{
  "scripts": {
    "lint": "tsc --noEmit && eslint '*/**/*.{js,ts,tsx}' --quiet --fix"
  }
}

The above script can be run from the command line using npm run lint or yarn lint. This command will first run the TypeScript compiler and report any TypeScript compiler errors. If there are no TypeScript errors, it will then run ESLint through all the .js, .ts, and .tsx (used with React) files. Any ESLint errors that can be automatically fixed will be fixed with this command, but any other errors will be printed out in the command line.

Preventing ESLint and formatting errors from being committed

To ensure all files committed to git don't have any TypeScript, linting, or formatting errors, there is a tool called lint-staged that can be used. lint-staged allows to run linting commands on files that are staged to be committed. When lint-staged is used in combination with husky, the linting commands specified with lint-staged can be executed to staged files on pre-commit (if unfamiliar with git hooks, read about them here).

To configure lint-staged and husky, add the following configuration to the package.json file:

{
  "husky": {
      "hooks": {
          "pre-commit": "lint-staged"
      }
  },
  "lint-staged": {
      "*.{js,ts,tsx}": [
          "eslint --fix",
          "git add"
      ]
  }
}

The above configuration will run lint-staged when a user tries to commit code to git. lint-staged will then run ESLint on any staged files with .js, .ts, and .tsx extensions. Any errors that can be fixed automatically will be fixed and added to the current commit. However, if there are any linting errors that cannot be fixed automatically, the commit will fail and the errors will need to be manually fixed before trying to commit the code again.

Personally, I also like to prevent any commits that would cause the TypeScript compiler to fail, therefore I like to add a check on pre-commit that also checks for TypeScript errors. The husky configuration can be modified to do so:

{
  "husky": {
      "hooks": {
          "pre-commit": "tsc --noEmit && lint-staged"
      }
  }
}

Unfortunately it is not enough to only rely on lint-staged and husky to prevent linting errors and TypeScript compiler errors since the git hooks can be by-passed if a user commits uses the --no-verify flag. Therefore, it is also recommended to run a command on a continuous integration (CI) server that will verify that the TypeScript compiler doesn't fail and that there are no linting errors. That command should look like the following:

tsc --noEmit && eslint '*/**/*.{js,ts,tsx}' --quiet

Notice the above command doesn't pass the --fix command to the eslint CLI since we want the command to fail if there are any sort of errors. We do not want to CI automatically fixing lint errors since that would indicate that there is code that does not pass the linting checks that has been committed to git.


That's how you can lint and format a TypeScript project using ESLint and Prettier 😎


See a typo? Edit post on GitHub
Categories:
Elegant Development Experience With Zsh and Hyper TerminalGet Started With Typescript in 2019