Skip to content
Search

ESLint

lastmod 2025-02-14created 2020-09-2537 edits

ESLint is a static code analysis tool for identifying problematic patterns found in JavaScript code. Rules in ESLint are configurable, and customized rules can be defined and loaded. ESLint covers both code quality and coding style issues.

Categories

Plugins

React

E.T.C

Command Line Interface

npx eslint [options] [file|dir|glob]*

Fix problems

  • --fix - Automatically fix problems
  • --fix-dry-run - Automatically fix problems without saving the changes to the file system
  • --fix-type Array - Specify the types of fixes to apply (directive, problem, suggestion, layout)

Configuration File Formats

ESLint supports configuration files in several formats.

  • JavaScript - use .eslintrc.js and export an object containing your configuration.
  • JavaScript (ESM) - use .eslintrc.cjs when running ESLint in JavaScript packages that specify "type":"module" in their package.json. Note that ESLint does not support ESM configuration at this time.
  • YAML - use .eslintrc.yaml or .eslintrc.yml to define the configuration structure.
  • JSON - use .eslintrc.json to define the configuration structure. ESLint's JSON files also allow JavaScript-style comments.
  • Deprecated - use .eslintrc, which can be either JSON or YAML.
  • package.json - create an eslintConfig property in your package.json file and define your configuration there.

If there are multiple configuration files in the same directory, ESLint uses only one. The order of priority is as follows.

  1. .eslintrc.js
  2. .eslintrc.cjs
  3. .eslintrc.yaml
  4. .eslintrc.yml
  5. .eslintrc.json
  6. .eslintrc
  7. package.json

You can easily create a configuration file with the following command:

yarn create @eslint/config
$ yarn create @eslint/config
yarn create v1.22.10
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Installed "@eslint/[email protected]" with binaries:
      - create-config
✔ How would you like to use ESLint? · style
✔ What type of modules does your project use? · esm
✔ Which framework does your project use? · none
✔ Does your project use TypeScript? · No / Yes
✔ Where does your code run? · browser
✔ How would you like to define a style for your project? · prompt
✔ What format do you want your config file to be in? · JSON
✔ What style of indentation do you use? · 4
✔ What quotes do you use for strings? · single
✔ What line endings do you use? · unix
✔ Do you require semicolons? · No / Yes
The config that you've selected requires the following dependencies:

@typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest
✔ Would you like to install them now with npm? · No / Yes
Installing @typescript-eslint/eslint-plugin@latest, @typescript-eslint/parser@latest
npm WARN rm not removing /home/your/Project/answer-dev/api/node_modules/.bin/semver as it wasn't installed by /home/your/Project/answer-dev/api/node_modules/semver
npm notice created a lockfile as package-lock.json. You should commit this file.
+ @typescript-eslint/[email protected]
+ @typescript-eslint/[email protected]
added 1 package from 1 contributor, removed 1 package, updated 373 packages and audited 387 packages in 13.706s

50 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Successfully created .eslintrc.json file in /home/your/Project/answer-dev/api
Done in 35.86s.

Options

root

ESLint can be configured with multiple configuration files. This is especially useful when several projects coexist in a single code repository, as in a Monorepo.

ESLint first checks whether there is a configuration file in the folder containing the file being linted, and if there isn't one, it looks for configuration files by moving up through the parent folders one level at a time. Once it meets a configuration file with the root option set to true, it stops going up to parent folders.

For example, if you set the root option to false in each project's configuration file and set it to true at the top level of the code repository, you can conveniently manage the repository's shared settings and the project-specific settings separately.

env

JavaScript can run in many environments, and each environment has its own objects accessible through global variables. A typical example is the window object, which is globally accessible in the browser environment but not in the NodeJS environment.

By default, ESLint raises errors for variables accessed without being declared first, so you have to tell it, through configuration, about the global objects that each runtime provides by default. The env option of the executable file handles this role.

For example, if the JavaScript code you lint with ESLint can run both in the browser and in NodeJS, you can register all global objects accessible in both runtimes as follows.

{
  "env": {
    "browser": true,
    "node": true
  }
}

plugins

ESLint has a wide range of plugins that let you use additional rules beyond the built-in rules. It would be no exaggeration to say that this powerful plugin ecosystem is exactly why ESLint became the most widely used linter in the JavaScript community.

Plugins are set through the plugins option of the configuration file. For example, rules related to imports (import) and React can be added as follows.

{
  "plugins": ["import", "react"]
}

Naturally, you need to have installed the plugins in the project as development dependencies first. Note that the npm package names of ESLint plugins usually start with eslint-plugin-.

$ npm i -D eslint-plugin-import eslint-plugin-react

A common misconception when setting up plugins is that simply adding a plugin enables the related rules right away. In fact, a plugin only makes new rules available for configuration. Whether a rule violation should raise an error (error), raise a warning (warn), or turn the rule off (off) has to be configured separately through the #extends or #rules options explained next.

extends

Many global companies such as Google, Facebook, and Airbnb lint their JavaScript code with ESLint. Through the extends option of the configuration file, you can take the configurations these companies have published as they are and use them as a base configuration.

For example, let's use eslint-config-airbnb, the ESLint configuration Airbnb published to the npm repository, as the base configuration.

{
  "extends": ["airbnb"]
}

Extendable ESLint configurations like this have npm package names starting with eslint-config-, and when you specify them in the extends option, you can omit that prefix as shown above.

In addition, most ESLint plugins provide recommended configurations. The extends option is also used to apply these recommended configurations.

For example, let's use the recommended configurations provided by the import and react plugins set up above.

{
  "plugins": ["import", "react"],
  "extends": ["plugin:import/recommended", "plugin:react/recommended"]
}

rules

The rules option in the configuration file is used to control each rule in detail. It is generally useful when you want to override rules set through the extends option.

For example, the Airbnb base configuration raises a warning (warn) when the no-console rule is violated and an error (error) when the import/prefer-default-export rule is violated. Let's make a no-console violation raise an error instead of a warning, and disable the import/prefer-default-export rule.

{
  "extends": ["airbnb"],
  "rules": {
    "no-console": "error",
    "import/prefer-default-export": "off"
  }
}

In this way, ESLint gives rules specified in the rules option priority over rules brought in through the extends option. Be careful, though: the more you use the rules option, the more configuration you have to manage yourself.

For maintainability, it is better to make active use of well-maintained public configurations from the JavaScript community through the extends option covered above.

parser, parserOptions

The JavaScript code developers write often differs from the code that actually runs in a runtime such as a browser. Typical examples are developing with JavaScript syntax extensions such as TypeScript or JSX, or developing with the latest syntax through a transpiler such as Babel.

For details onBabel, a tool that helps developers always code in JavaScript with the latest syntax, see the related tags.

By default, ESLint only understands plain JavaScript code, so to lint code written with JavaScript syntax extensions or the latest syntax, you have to configure it to use a matching parser.

For example, let's configure it to lint code written with TypeScript and JSX.

{
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 11,
  }
}

This time, let's configure it to use the Babel parser.

{
  "parser": "@babel/eslint-parser"
}

Of course, to use that parser you have to install the related package.

settings

Some ESLint plugins allow additional configuration. In that case, use the settings option of the configuration file.

For example, let's configure the react plugin to automatically detect the version of React installed in the project. (By default, linting is based on the latest version of React.)

{
  "settings": {
    "react": {
      "version": "detect"
    }
  }
}

For how to configure other plugins, refer to the official documentation of each plugin.

ignorePatterns

When linting, ESLint ignores the node_modules folder and configuration files starting with . by default. If you want to ignore other files as well, you can use the ignorePatterns option of the configuration file.

{
  "ignorePatterns": ["build", "dist", "public"]
}

Instead, you can also create an .eslintignore file, which works much like a .gitignore file.

If you want ESLint to ignore the paths already listed in your .gitignore file, add the --ignore-path option when running the ESLint command.

eslint --ignore-path .gitignore .

overrides

What should you do when only some files in a project need slightly different settings? In that case, use the overrides option of the configuration file.

For example, if JavaScript files and TypeScript files coexist in a project, you can make the base configuration for JavaScript files and specify the configuration for TypeScript files in the overrides option. Here, files with TypeScript extensions are set to use the TypeScript parser, plugin, and recommended configuration.

{
  "overrides": [
    {
      "files": "**/*.+(ts|tsx)",
      "parser": "@typescript-eslint/parser",
      "plugins": ["@typescript-eslint"],
      "extends": ["plugin:@typescript-eslint/recommended"]
    }
  ]
}

If you want to additionally enable the rules recommended by the Jest plugin and the Testing Library plugin only for the test files in a project, configure it as follows.

{
  "overrides": [
    {
      "files": ["**/__tests__/**/*", "**/*.{spec,test}.*"],
      "env": {
        "jest/globals": true
      },
      "plugins": ["jest", "testing-library"],
        "extends": [
        "plugin:jest/recommended",
        "plugin:jest-dom/recommended",
        "plugin:testing-library/react"
      ]
    }
  ]
}

Default .eslintrc.js

// https://eslint.org/docs/user-guide/configuring
module.exports = {
  root: true,
  parser: 'babel-eslint',
  parserOptions: {
  sourceType: 'module'
  },
  env: {
    browser: true,
  },
  // https://github.com/standard/standard/blob/master/docs/RULES-en.md
  extends: 'standard',
  // required to lint *.vue files
  plugins: [
    'html'
  ],
  // add your custom rules here
  rules: {
    // allow async-await
    'generator-star-spacing': 'off',
    // allow debugger during development
   'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
  }
}

Inline ignore

/* eslint-disable */
console.log('JavaScript debug log');
console.log('eslint is disabled now');
/* eslint-enable */

Disabling specific ESLint rules

/* eslint-disable no-console, no-control-regex*/
console.log('JavaScript debug log');
console.log('eslint is disabled now');

Ignore a single line

console.log('eslint is disabled for the current line'); // eslint-disable-line
// eslint-disable-next-line
console.log('eslint is disabled for the current line');

Ignore rules

When you build, errors like the following may occur.

Module Error (from ./node_modules/eslint-loader/index.js):

/Users/your/Project/c2web/src/components/Canvas/acvPainter.vue
   83:5   error    Identifier 'hide_event' is not in camel case        @typescript-eslint/camelcase
  267:11  error    Unexpected var, use let or const instead            no-var
  267:15  error    'width' is already defined                          no-redeclare
  955:17  error    'event_area' is not defined                         no-undef
  967:13  error    Unexpected empty method 'created'                   @typescript-eslint/no-empty-function

✖ 267 problems (266 errors, 1 warning)
  82 errors and 0 warnings potentially fixable with the `--fix` option.

The name of the detected Rule is printed to the right of each error message. Switch the rule with that name to off.

  "eslintConfig": {
    "rules": {
      "camelcase": "off",
      "@typescript-eslint/camelcase": "off"
    }
  }

Troubleshooting

Using the export keyword between a decorator and a class is not allowed. Please use export @dec class instead

The following error message may be printed.

eslint Parsing error: Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.

Add the following to the configuration file.

{
  parserOptions: {
    ecmaFeatures: {
      legacyDecorators: true
    }
  }
}

ESLint Parsing error: Unexpected token

Add babel-eslint.

$ npm install --save-dev babel-eslint

Select babel-eslint as the parser.

{
  parserOptions: {
    parser: "babel-eslint"
  }
}

Resolve Error: typescript with invalid interface loaded as resolver ESLint

An issue on the eslint-plugin-import side. To apply typescript, you also need to install eslint-import-resolver-typescript.

=== SyntaxError: Failed to load plugin '@typescript-eslint' declared in 'package.json': Unexpected token '||=' ===

SyntaxError: Failed to load plugin '@typescript-eslint' declared in 'package.json': Unexpected token '||='
Referenced from: /home/your/Project/ui/package.json

/home/your/Project/ui/node_modules/@typescript-eslint/scope-manager/dist/referencer/ClassVisitor.js:123
        withMethodDecorators ||=
                             ^^^

SyntaxError: Unexpected token '||='
    at wrapSafe (internal/modules/cjs/loader.js:1029:16)
    at Module._compile (internal/modules/cjs/loader.js:1078:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1143:10)
    at Module.load (internal/modules/cjs/loader.js:979:32)
    at Function.Module._load (internal/modules/cjs/loader.js:819:12)
    at Module.require (internal/modules/cjs/loader.js:1003:19)
    at require (internal/modules/cjs/helpers.js:107:18)
    at Object.<anonymous> (/home/your/Project/ui/node_modules/@typescript-eslint/scope-manager/dist/referencer/Referencer.js:20:24)
    at Module._compile (internal/modules/cjs/loader.js:1114:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1143:10)
Process finished with exit code -1

The node version setting seems to be wrong. Check the node settings in PyCharm.

See also

Favorite site

Guide

author Zer0 sitemap