How to use ESLint in Node.js applications

created at 08-09-2021 views: 7

Instroduction

ESLint is an open source JavaScript linting utility that can help you overcome developer errors because JavaScript is a weakly typed language.

There are many options in the Javascript community, such as JSHint and JSCS, for code linting, including ESLint, which we are going to talk about today.

ESLint aims to make all rules fully pluggable. This is one of the main reasons for it. It allows developers to create their own linting rules. Each rule provided in the official ESLint guide is an independent rule, and the developer can decide whether to use a specific rule at any time.

Install

For local installation of the project directory:

$ npm i eslint -D

For the global installation in the working system:

$ npm i eslint -g

ESLint can now be used through the eslint command in the terminal.

Configuration

The simplest configuration method is to set up a .eslintrc JSON file, which can describe all the linting rules.

An example of .eslintrc:

{
  "env": {
    "node": true,
    "browser": true
  },
  "rules": {
    "no-console": 0,
    "space-infix-ops": "error",
    "quotes": ["error", "single", {
      "avoidEscape": true,
      "allowTemplateLiterals": true
    }],
    "space-before-blocks": ["error", "always"],
    "semi": ["error", "never"]
  },
  "plugins": []
}

Main fields:

  • parse — specify the parser
  • parserOptions — specify parser options
  • env — Specify the script's running environment
  • root — When true, stop looking up the configuration file in the parent directory
  • globals — additional global variables accessed by the script during execution
    rules — add your custom rules here

If eslint is installed globally, we can also use the following command to generate a configuration file:

$ eslint --init

In other cases, if you have installed it into the project locally, you need to enter in the terminal:

$ ./node_modules/.bin/eslint --init

In both cases, you will be prompted to generate a set of basic rules for the .eslintrc file.

prompt of generating a set of basic rules for the .eslintrc file

Examples of files generated after the above prompts:

{
  "env": {
    "browser": true,
    "commonjs": true,
    "es2021": true
  },
  "extends": "eslint:recommended",
  "parserOptions": {
    "ecmaVersion": 12
  },
  "rules": {
    "indent": [
      "error",
      "tab"
    ],
    "linebreak-style": [
      "error",
      "windows"
    ],
    "quotes": [
      "error",
      "single"
    ],
    "semi": [
      "error",
      "never"
    ]
  }
}

more details of configuration you can found: here

In order to facilitate the operation, we open the package.json of the project and add the following script in the scripts field:

{
  "scripts" : {
    "lint": "eslint **/*.js",
    "lint-html": "eslint **/*.js -f html -o ./reports/lint-results.html",
    "lint-fix": "eslint --fix **/*.js"
  }
}

We apply this rule to the following files:

var a = 1;
console.log(1);

After executing npm run lint, the following message will appear:

message after npm run lint

The ESLint prompt is already obvious: 3 errors. There is an extra semicolon error at the end of the first and second lines, a is assigned but never used.

And it is prompted to use the --fix option to fix errors and warnings. There are 2 errors that can be fixed. Now, use npm run lint-fix to fix it, and whether or not a depends on manual changes.

You can also run the npm run lint-html command to write the check results into a web page file.

npm run lint-html

Profile priority

If you follow the above steps step by step, you may already know that ESLint supports several formats of configuration files.

Now there is a question. If there are multiple ESLint files in the same directory, how will they be executed and what is the priority?

Our answer is given in the ESLint source code, and its priority configuration is as follows:

const configFilenames = [
  ".eslintrc.js",
  ".eslintrc.yaml",
  ".eslintrc.yml",
  ".eslintrc.json",
  ".eslintrc",
  "package.json"
]

.eslintrc.js > .eslintrc.yaml > .eslintrc.yml > .eslintrc.json > .eslintrc > package.json

rule

The rules in ESLint are added separately. No rules are enforced by default. You must specify the rule explicitly before enabling it for the linting process.

Find the complete list of rules in the official documentation.

After deciding which rules to include, you must set these error levels. Each error level can be defined as follows:

  • 0 — Turn off the rule, equivalent to off
  • 1 — Turn on the rule as a warning, equivalent to warn
  • 2 — Open the rule as an error, equivalent to error

The difference between errors and warnings is the exit code that eslint will have when it completes. If any errors are found, eslint will exit with an exit code of 1, otherwise it will exit with 0.

If you lint during the build step, this allows you to control which rules should break your build and which rules should be treated as warnings.

environment

The code you are writing may be suitable for a specific environment, for example, you may be using the Express framework to write a REST API in a Node.js application, and the front end of the application will be built in Vue/React.

Two different projects, two different environments, they can all have separate eslint configuration in one file, even if the client and server are located in a project directory that is regarded as the project root directory.

How is it done?

By setting the environment id to true in the "env" section of .eslintrc.

ESLint CLI

ESLint comes with a command line interface (CLI) for lint files or directories.

$ eslint index.js

As we have seen in the previous example, the output generated after running the command will be grouped by file and will specify the line:column warning/error, the reason for the error, and the rule name for each failure.

Combine ESLint with your favorite coding style

ESLint personally does not advocate any coding style. You can set the .eslintrc file to enforce the encoding style using your favorite style rules.

You can also use ESLint with style guides (such as Airbnb, JavaScript standard style).

You must also use additional plugins, such as:

  • Airbnb’s plugin eslint-config-airbnb-base.
  • JavaScript standard style eslint-config-standard
  • Some popular library plugins: Vue | React

Team norms

The progressive ESLint configuration (eslint-config-alloy) of the React/Vue/TypeScript project given by AlloyTeam, a small part of the React configuration is posted below:

module.exports = {
  parserOptions: {
    babelOptions: {
      presets: ['@babel/preset-react'],
    },
  },
  plugins: ['react'],
  rules: {
    /**
     * The name of propTypes of boolean type must start with is or has
     * @reason type-related constraints are handed over to TypeScript
     */
    'react/boolean-prop-naming': 'off',
    /**
     * <button> must have a type attribute
     */
    'react/button-has-type': 'off',
    /**
     * A defaultProps must have corresponding propTypes
     * @reason type-related constraints are handed over to TypeScript
     */
    'react/default-props-match-prop-types': 'off',
    /**
     * props, state, context must be assigned with destructuring
     */
    'react/destructuring-assignment': 'off',
    /**
     * The component must have a displayName property
     * @reason is not mandatory to write displayName
     */
    'react/display-name': 'off',
    // ...
  }
}
created at:08-09-2021
edited at: 08-09-2021: