Skip to content

Instantly share code, notes, and snippets.

@bgoonz
Last active May 29, 2022 11:44
Show Gist options
  • Save bgoonz/e6e0f8bb8e9bfa689a1c6a860011d8d0 to your computer and use it in GitHub Desktop.
Save bgoonz/e6e0f8bb8e9bfa689a1c6a860011d8d0 to your computer and use it in GitHub Desktop.
ESLINT

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.
  • 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 will only use one. The priority order is as follows:

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

Using Configuration Files

There are two ways to use configuration files.

The first way to use configuration files is via .eslintrc.* and package.json files. ESLint will automatically look for them in the directory of the file to be linted, and in successive parent directories all the way up to the root directory of the filesystem (/), the home directory of the current user (~/), or when root: true is specified. See Cascading and Hierarchy below for more details on this. Configuration files can be useful when you want different configurations for different parts of a project or when you want others to be able to use ESLint directly without needing to remember to pass in the configuration file.

The second way to use configuration files is to save the file wherever you would like and pass its location to the CLI using the --config option, such as:

eslint -c myconfig.json myfiletotest.js

If you are using one configuration file and want ESLint to ignore any .eslintrc.* files, make sure to use --no-eslintrc along with the -c flag.

Here's an example JSON configuration file that uses the typescript-eslint parser to support TypeScript syntax:

{
    "root": true,
    "extends": [
        "eslint:recommended",
        "plugin:@typescript-eslint/recommended"
    ],
    "parser": "@typescript-eslint/parser",
    "parserOptions": { "project": ["./tsconfig.json"] },
    "plugins": [
        "@typescript-eslint"
    ],
    "rules": {
        "@typescript-eslint/strict-boolean-expressions": [
            2,
            {
                "allowString" : false,
                "allowNumber" : false
            }
        ]
    },
    "ignorePatterns": ["src/**/*.test.ts", "src/frontend/generated/*"]
}

Both the JSON and YAML configuration file formats support comments (package.json files should not include them). You can use JavaScript-style comments for JSON files and YAML-style comments for YAML files. ESLint safely ignores comments in configuration files. This allows your configuration files to be more human-friendly.

For JavaScript-style comments:

{
    "env": {
        "browser": true
    },
    "rules": {
        // Override our default settings just for this directory
        "eqeqeq": "warn",
        "strict": "off"
    }
}

For YAML-style comments:

env:
    browser: true
rules:
    # Override default settings
    eqeqeq: warn
    strict: off

ESLint supports adding shared settings into configuration files. Plugins use settings to specify information that should be shared across all of its rules. You can add settings object to ESLint configuration file and it will be supplied to every rule being executed. This may be useful if you are adding custom rules and want them to have access to the same information and be easily configurable.

In JSON:

{
    "settings": {
        "sharedData": "Hello"
    }
}

And in YAML:

---
  settings:
    sharedData: "Hello"

Cascading and Hierarchy

When using .eslintrc.* and package.json files for configuration, you can take advantage of configuration cascading. Suppose you have the following structure:

your-project
├── .eslintrc.json
├── lib
│ └── source.js
└─┬ tests
  ├── .eslintrc.json
  └── test.js

The configuration cascade works based on the location of the file being linted. If there is a .eslintrc file in the same directory as the file being linted, then that configuration takes precedence. ESLint then searches up the directory structure, merging any .eslintrc files it finds along the way until reaching either a .eslintrc file with root: true or the root directory.

In the same way, if there is a package.json file in the root directory with an eslintConfig field, the configuration it describes will apply to all subdirectories beneath it, but the configuration described by the .eslintrc file in the tests/ directory will override it where there are conflicting specifications.

your-project
├── package.json
├── lib
│ └── source.js
└─┬ tests
  ├── .eslintrc.json
  └── test.js

If there is a .eslintrc and a package.json file found in the same directory, .eslintrc will take priority and package.json file will not be used.

By default, ESLint will look for configuration files in all parent folders up to the root directory. This can be useful if you want all of your projects to follow a certain convention, but can sometimes lead to unexpected results. To limit ESLint to a specific project, place "root": true inside the .eslintrc.* file or eslintConfig field of the package.json file or in the .eslintrc.* file at your project's root level. ESLint will stop looking in parent folders once it finds a configuration with "root": true.

{
    "root": true
}

And in YAML:

---
  root: true

For example, consider projectA which has "root": true set in the .eslintrc file in the lib/ directory. In this case, while linting main.js, the configurations within lib/ will be used, but the .eslintrc file in projectA/ will not.

home
└── user
    └── projectA
        ├── .eslintrc.json  <- Not used
        └── lib
            ├── .eslintrc.json  <- { "root": true }
            └── main.js

The complete configuration hierarchy, from highest to lowest precedence, is as follows:

  1. Inline configuration
    1. /*eslint-disable*/ and /*eslint-enable*/
    2. /*global*/
    3. /*eslint*/
    4. /*eslint-env*/
  2. Command line options (or CLIEngine equivalents):
    1. --global
    2. --rule
    3. --env
    4. -c, --config
  3. Project-level configuration:
    1. .eslintrc.* or package.json file in the same directory as the linted file
    2. Continue searching for .eslintrc.* and package.json files in ancestor directories up to and including the root directory or until a config with "root": true is found.

Please note that the home directory of the current user on your preferred operating system (~/) is also considered a root directory in this context and searching for configuration files will stop there as well. And with the removal of support for Personal Configuration Files from the 8.0.0 release forward, configuration files present in that directory will be ignored.

Extending Configuration Files

A configuration file, once extended, can inherit all the traits of another configuration file (including rules, plugins, and language options) and modify all the options. As a result, there are three configurations, as defined below:

  • Base config: the configuration that is extended.
  • Derived config: the configuration that extends the base configuration.
  • Resulting actual config: the result of merging the derived configuration into the base configuration.

The extends property value is either:

  • a string that specifies a configuration (either a path to a config file, the name of a shareable config, eslint:recommended, or eslint:all)
  • an array of strings where each additional configuration extends the preceding configurations

ESLint extends configurations recursively, so a base configuration can also have an extends property. Relative paths and shareable config names in an extends property are resolved from the location of the config file where they appear.

The eslint-config- prefix can be omitted from the configuration name. For example, airbnb resolves as eslint-config-airbnb.

The rules property can do any of the following to extend (or override) the set of rules:

  • enable additional rules
  • change an inherited rule's severity without changing its options:
    • Base config: "eqeqeq": ["error", "allow-null"]
    • Derived config: "eqeqeq": "warn"
    • Resulting actual config: "eqeqeq": ["warn", "allow-null"]
  • override options for rules from base configurations:
    • Base config: "quotes": ["error", "single", "avoid-escape"]
    • Derived config: "quotes": ["error", "single"]
    • Resulting actual config: "quotes": ["error", "single"]
  • override options for rules given as object from base configurations:
    • Base config: "max-lines": ["error", { "max": 200, "skipBlankLines": true, "skipComments": true }]
    • Derived config: "max-lines": ["error", { "max": 100 }]
    • Resulting actual config: "max-lines": ["error", { "max": 100 }] where skipBlankLines and skipComments default to false

Using a shareable configuration package

A sharable configuration is an npm package that exports a configuration object. Make sure that you have installed the package in your project root directory, so that ESLint can require it.

The extends property value can omit the eslint-config- prefix of the package name.

The npm init @eslint/config command can create a configuration so you can extend a popular style guide (for example, eslint-config-standard).

Example of a configuration file in YAML format:

extends: standard
rules:
  comma-dangle:
    - error
    - always
  no-empty: warn

Using eslint:recommended

Using "eslint:recommended" in the extends property enables a subset of core rules that report common problems (these rules are identified with a checkmark ✓ on the rules page).

Here's an example of extending eslint:recommended and overriding some of the set configuration options:

Example of a configuration file in JavaScript format:

module.exports = {
    "extends": "eslint:recommended",
    "rules": {
        // enable additional rules
        "indent": ["error", 4],
        "linebreak-style": ["error", "unix"],
        "quotes": ["error", "double"],
        "semi": ["error", "always"],

        // override configuration set by extending "eslint:recommended"
        "no-empty": "warn",
        "no-cond-assign": ["error", "always"],

        // disable rules from base configurations
         "for-direction": "off",
    }
}

Using a configuration from a plugin

A plugin is an npm package that can add various extensions to ESLint. A plugin can perform numerous functions, including but not limited to adding new rules and exporting shareable configurations. Make sure the package has been installed in a directory where ESLint can require it.

The plugins property value can omit the eslint-plugin- prefix of the package name.

The extends property value can consist of:

  • plugin:
  • the package name (from which you can omit the prefix, for example, react is short for eslint-plugin-react)
  • /
  • the configuration name (for example, recommended)

Example of a configuration file in JSON format:

{
    "plugins": [
        "react"
    ],
    "extends": [
        "eslint:recommended",
        "plugin:react/recommended"
    ],
    "rules": {
       "react/no-set-state": "off"
    }
}

Using a configuration file

The extends property value can be an absolute or relative path to a base configuration file. ESLint resolves a relative path to a base configuration file relative to the configuration file that uses it.

Example of a configuration file in JSON format:

{
    "extends": [
        "./node_modules/coding-standard/eslintDefaults.js",
        "./node_modules/coding-standard/.eslintrc-es6",
        "./node_modules/coding-standard/.eslintrc-jsx"
    ],
    "rules": {
        "eqeqeq": "warn"
    }
}

Using "eslint:all"

The extends property value can be "eslint:all" to enable all core rules in the currently installed version of ESLint. The set of core rules can change at any minor or major version of ESLint.

Important: This configuration is not recommended for production use because it changes with every minor and major version of ESLint. Use it at your own risk.

You might enable all core rules as a shortcut to explore rules and options while you decide on the configuration for a project, especially if you rarely override options or disable rules. The default options for rules are not endorsements by ESLint (for example, the default option for the quotes rule does not mean double quotes are better than single quotes).

If your configuration extends eslint:all, after you upgrade to a newer major or minor version of ESLint, review the reported problems before you use the --fix option on the command line, so you know if a new fixable rule will make changes to the code.

Example of a configuration file in JavaScript format:

module.exports = {
    "extends": "eslint:all",
    "rules": {
        // override default options
        "comma-dangle": ["error", "always"],
        "indent": ["error", 2],
        "no-cond-assign": ["error", "always"],

        // disable now, but enable in the future
        "one-var": "off", // ["error", "never"]

        // disable
        "init-declarations": "off",
        "no-console": "off",
        "no-inline-comments": "off",
    }
}

Configuration Based on Glob Patterns

v4.1.0+. Sometimes a more fine-controlled configuration is necessary, for example, if the configuration for files within the same directory has to be different. Therefore you can provide configurations under the overrides key that will only apply to files that match specific glob patterns, using the same format you would pass on the command line (e.g., app/**/*.test.js).

Glob patterns in overrides use minimatch syntax.

How do overrides work?

It is possible to override settings based on file glob patterns in your configuration by using the overrides key. An example of using the overrides key is as follows:

In your .eslintrc.json:

{
  "rules": {
    "quotes": ["error", "double"]
  },

  "overrides": [
    {
      "files": ["bin/*.js", "lib/*.js"],
      "excludedFiles": "*.test.js",
      "rules": {
        "quotes": ["error", "single"]
      }
    }
  ]
}

Here is how overrides work in a configuration file:

  • The patterns are applied against the file path relative to the directory of the config file. For example, if your config file has the path /Users/john/workspace/any-project/.eslintrc.js and the file you want to lint has the path /Users/john/workspace/any-project/lib/util.js, then the pattern provided in .eslintrc.js will be executed against the relative path lib/util.js.
  • Glob pattern overrides have higher precedence than the regular configuration in the same config file. Multiple overrides within the same config are applied in order. That is, the last override block in a config file always has the highest precedence.
  • A glob specific configuration works almost the same as any other ESLint config. Override blocks can contain any configuration options that are valid in a regular config, with the exception of root and ignorePatterns.
    • A glob specific configuration can have an extends setting, but the root property in the extended configs is ignored. The ignorePatterns property in the extended configs is used only for the files the glob specific configuration matched.
    • Nested overrides setting will be applied only if the glob patterns of both of the parent config and the child config matched. This is the same when the extended configs have an overrides setting.
  • Multiple glob patterns can be provided within a single override block. A file must match at least one of the supplied patterns for the configuration to apply.
  • Override blocks can also specify patterns to exclude from matches. If a file matches any of the excluded patterns, the configuration won't apply.

Relative glob patterns

project-root
├── app
│   ├── lib
│   │   ├── foo.js
│   │   ├── fooSpec.js
│   ├── components
│   │   ├── bar.js
│   │   ├── barSpec.js
│   ├── .eslintrc.json
├── server
│   ├── server.js
│   ├── serverSpec.js
├── .eslintrc.json

The config in app/.eslintrc.json defines the glob pattern **/*Spec.js. This pattern is relative to the base directory of app/.eslintrc.json. So, this pattern would match app/lib/fooSpec.js and app/components/barSpec.js but NOT server/serverSpec.js. If you defined the same pattern in the .eslintrc.json file within in the project-root folder, it would match all three of the *Spec files.

If a config is provided via the --config CLI option, the glob patterns in the config are relative to the current working directory rather than the base directory of the given config. For example, if --config configs/.eslintrc.json is present, the glob patterns in the config are relative to . rather than ./configs.

Specifying target files to lint

If you specified directories with CLI (e.g., eslint lib), ESLint searches target files in the directory to lint. The target files are *.js or the files that match any of overrides entries (but exclude entries that are any of files end with *).

If you specified the --ext command line option along with directories, the target files are only the files that have specified file extensions regardless of overrides entries.

Personal Configuration Files (deprecated)

⚠️ This feature has been deprecated. This feature will be removed in the 8.0.0 release. If you want to continue to use personal configuration files, please use the --config CLI option. For more information regarding this decision, please see RFC 28 and RFC 32.

~/ refers to the home directory of the current user on your preferred operating system. The personal configuration file being referred to here is ~/.eslintrc.* file, which is currently handled differently than other configuration files.

How does ESLint find personal configuration files?

If eslint could not find any configuration file in the project, eslint loads ~/.eslintrc.* file.

If eslint could find configuration files in the project, eslint ignores ~/.eslintrc.* file even if it's in an ancestor directory of the project directory.

How do personal configuration files behave?

~/.eslintrc.* files behave similarly to regular configuration files, with some exceptions:

~/.eslintrc.* files load shareable configs and custom parsers from ~/node_modules/ – similarly to require() – in the user's home directory. Please note that it doesn't load global-installed packages.

~/.eslintrc.* files load plugins from $CWD/node_modules by default in order to identify plugins uniquely. If you want to use plugins with ~/.eslintrc.* files, plugins must be installed locally per project. Alternatively, you can use the --resolve-plugins-relative-to CLI option to change the location from which ESLint loads plugins.

Specifying Environments

An environment provides predefined global variables. The available environments are:

  • browser - browser global variables.
  • node - Node.js global variables and Node.js scoping.
  • commonjs - CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack).
  • shared-node-browser - Globals common to both Node.js and Browser.
  • es6 - enable all ECMAScript 6 features except for modules (this automatically sets the ecmaVersion parser option to 6).
  • es2016 - adds all ECMAScript 2016 globals and automatically sets the ecmaVersion parser option to 7.
  • es2017 - adds all ECMAScript 2017 globals and automatically sets the ecmaVersion parser option to 8.
  • es2018 - adds all ECMAScript 2018 globals and automatically sets the ecmaVersion parser option to 9.
  • es2019 - adds all ECMAScript 2019 globals and automatically sets the ecmaVersion parser option to 10.
  • es2020 - adds all ECMAScript 2020 globals and automatically sets the ecmaVersion parser option to 11.
  • es2021 - adds all ECMAScript 2021 globals and automatically sets the ecmaVersion parser option to 12.
  • es2022 - adds all ECMAScript 2022 globals and automatically sets the ecmaVersion parser option to 13.
  • worker - web workers global variables.
  • amd - defines require() and define() as global variables as per the amd spec.
  • mocha - adds all of the Mocha testing global variables.
  • jasmine - adds all of the Jasmine testing global variables for version 1.3 and 2.0.
  • jest - Jest global variables.
  • phantomjs - PhantomJS global variables.
  • protractor - Protractor global variables.
  • qunit - QUnit global variables.
  • jquery - jQuery global variables.
  • prototypejs - Prototype.js global variables.
  • shelljs - ShellJS global variables.
  • meteor - Meteor global variables.
  • mongo - MongoDB global variables.
  • applescript - AppleScript global variables.
  • nashorn - Java 8 Nashorn global variables.
  • serviceworker - Service Worker global variables.
  • atomtest - Atom test helper globals.
  • embertest - Ember test helper globals.
  • webextensions - WebExtensions globals.
  • greasemonkey - GreaseMonkey globals.

These environments are not mutually exclusive, so you can define more than one at a time.

Environments can be specified inside of a file, in configuration files or using the --env command line flag.

To specify environments using a comment inside of your JavaScript file, use the following format:

/* eslint-env node, mocha */

This enables Node.js and Mocha environments.

Using configuration files

To specify environments in a configuration file, use the env key and specify which environments you want to enable by setting each to true. For example, the following enables the browser and Node.js environments:

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

Or in a package.json file

{
    "name": "mypackage",
    "version": "0.0.1",
    "eslintConfig": {
        "env": {
            "browser": true,
            "node": true
        }
    }
}

And in YAML:

---
  env:
    browser: true
    node: true

Using a plugin

If you want to use an environment from a plugin, be sure to specify the plugin name in the plugins array and then use the unprefixed plugin name, followed by a slash, followed by the environment name. For example:

{
    "plugins": ["example"],
    "env": {
        "example/custom": true
    }
}

Or in a package.json file

{
    "name": "mypackage",
    "version": "0.0.1",
    "eslintConfig": {
        "plugins": ["example"],
        "env": {
            "example/custom": true
        }
    }
}

Specifying Globals

Some of ESLint's core rules rely on knowledge of the global variables available to your code at runtime. Since these can vary greatly between different environments as well as be modified at runtime, ESLint makes no assumptions about what global variables exist in your execution environment. If you would like to use rules that require knowledge of what global variables are available, you can define global variables in your configuration file or by using configuration comments in your source code.

To specify globals using a comment inside of your JavaScript file, use the following format:

/* global var1, var2 */

This defines two global variables, var1 and var2. If you want to optionally specify that these global variables can be written to (rather than only being read), then you can set each with a "writable" flag:

/* global var1:writable, var2:writable */

Using configuration files

To configure global variables inside of a configuration file, set the globals configuration property to an object containing keys named for each of the global variables you want to use. For each global variable key, set the corresponding value equal to "writable" to allow the variable to be overwritten or "readonly" to disallow overwriting. For example:

{
    "globals": {
        "var1": "writable",
        "var2": "readonly"
    }
}

And in YAML:

---
  globals:
    var1: writable
    var2: readonly

These examples allow var1 to be overwritten in your code, but disallow it for var2.

Globals can be disabled with the string "off". For example, in an environment where most ES2015 globals are available but Promise is unavailable, you might use this config:

{
    "env": {
        "es6": true
    },
    "globals": {
        "Promise": "off"
    }
}

For historical reasons, the boolean value false and the string value "readable" are equivalent to "readonly". Similarly, the boolean value true and the string value "writeable" are equivalent to "writable". However, the use of older values is deprecated.

Specifying Parser Options

ESLint allows you to specify the JavaScript language options you want to support. By default, ESLint expects ECMAScript 5 syntax. You can override that setting to enable support for other ECMAScript versions as well as JSX by using parser options.

Please note that supporting JSX syntax is not the same as supporting React. React applies specific semantics to JSX syntax that ESLint doesn't recognize. We recommend using eslint-plugin-react if you are using React and want React semantics. By the same token, supporting ES6 syntax is not the same as supporting new ES6 globals (e.g., new types such as Set). For ES6 syntax, use { "parserOptions": { "ecmaVersion": 6 } }; for new ES6 global variables, use { "env": { "es6": true } }. { "env": { "es6": true } } enables ES6 syntax automatically, but { "parserOptions": { "ecmaVersion": 6 } } does not enable ES6 globals automatically.

Parser options are set in your .eslintrc.* file by using the parserOptions property. The available options are:

  • ecmaVersion - set to 3, 5 (default), 6, 7, 8, 9, 10, 11, 12, or 13 to specify the version of ECMAScript syntax you want to use. You can also set to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), 2019 (same as 10), 2020 (same as 11), 2021 (same as 12), or 2022 (same as 13) to use the year-based naming. You can also set "latest" to use the most recently supported version.
  • sourceType - set to "script" (default) or "module" if your code is in ECMAScript modules.
  • allowReserved - allow the use of reserved words as identifiers (if ecmaVersion is 3).
  • ecmaFeatures - an object indicating which additional language features you'd like to use:
    • globalReturn - allow return statements in the global scope
    • impliedStrict - enable global strict mode (if ecmaVersion is 5 or greater)
    • jsx - enable JSX

Here's an example .eslintrc.json file:

{
    "parserOptions": {
        "ecmaVersion": "latest",
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true
        }
    },
    "rules": {
        "semi": "error"
    }
}

Setting parser options helps ESLint determine what is a parsing error. All language options are false by default.

Specifying Environments

An environment provides predefined global variables. The available environments are:

  • browser - browser global variables.
  • node - Node.js global variables and Node.js scoping.
  • commonjs - CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack).
  • shared-node-browser - Globals common to both Node.js and Browser.
  • es6 - enable all ECMAScript 6 features except for modules (this automatically sets the ecmaVersion parser option to 6).
  • es2016 - adds all ECMAScript 2016 globals and automatically sets the ecmaVersion parser option to 7.
  • es2017 - adds all ECMAScript 2017 globals and automatically sets the ecmaVersion parser option to 8.
  • es2018 - adds all ECMAScript 2018 globals and automatically sets the ecmaVersion parser option to 9.
  • es2019 - adds all ECMAScript 2019 globals and automatically sets the ecmaVersion parser option to 10.
  • es2020 - adds all ECMAScript 2020 globals and automatically sets the ecmaVersion parser option to 11.
  • es2021 - adds all ECMAScript 2021 globals and automatically sets the ecmaVersion parser option to 12.
  • es2022 - adds all ECMAScript 2022 globals and automatically sets the ecmaVersion parser option to 13.
  • worker - web workers global variables.
  • amd - defines require() and define() as global variables as per the amd spec.
  • mocha - adds all of the Mocha testing global variables.
  • jasmine - adds all of the Jasmine testing global variables for version 1.3 and 2.0.
  • jest - Jest global variables.
  • phantomjs - PhantomJS global variables.
  • protractor - Protractor global variables.
  • qunit - QUnit global variables.
  • jquery - jQuery global variables.
  • prototypejs - Prototype.js global variables.
  • shelljs - ShellJS global variables.
  • meteor - Meteor global variables.
  • mongo - MongoDB global variables.
  • applescript - AppleScript global variables.
  • nashorn - Java 8 Nashorn global variables.
  • serviceworker - Service Worker global variables.
  • atomtest - Atom test helper globals.
  • embertest - Ember test helper globals.
  • webextensions - WebExtensions globals.
  • greasemonkey - GreaseMonkey globals.

These environments are not mutually exclusive, so you can define more than one at a time.

Environments can be specified inside of a file, in configuration files or using the --env command line flag.

To specify environments using a comment inside of your JavaScript file, use the following format:

/* eslint-env node, mocha */

This enables Node.js and Mocha environments.

Using configuration files

To specify environments in a configuration file, use the env key and specify which environments you want to enable by setting each to true. For example, the following enables the browser and Node.js environments:

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

Or in a package.json file

{
    "name": "mypackage",
    "version": "0.0.1",
    "eslintConfig": {
        "env": {
            "browser": true,
            "node": true
        }
    }
}

And in YAML:

---
  env:
    browser: true
    node: true

Using a plugin

If you want to use an environment from a plugin, be sure to specify the plugin name in the plugins array and then use the unprefixed plugin name, followed by a slash, followed by the environment name. For example:

{
    "plugins": ["example"],
    "env": {
        "example/custom": true
    }
}

Or in a package.json file

{
    "name": "mypackage",
    "version": "0.0.1",
    "eslintConfig": {
        "plugins": ["example"],
        "env": {
            "example/custom": true
        }
    }
}

Specifying Globals

Some of ESLint's core rules rely on knowledge of the global variables available to your code at runtime. Since these can vary greatly between different environments as well as be modified at runtime, ESLint makes no assumptions about what global variables exist in your execution environment. If you would like to use rules that require knowledge of what global variables are available, you can define global variables in your configuration file or by using configuration comments in your source code.

To specify globals using a comment inside of your JavaScript file, use the following format:

/* global var1, var2 */

This defines two global variables, var1 and var2. If you want to optionally specify that these global variables can be written to (rather than only being read), then you can set each with a "writable" flag:

/* global var1:writable, var2:writable */

Using configuration files

To configure global variables inside of a configuration file, set the globals configuration property to an object containing keys named for each of the global variables you want to use. For each global variable key, set the corresponding value equal to "writable" to allow the variable to be overwritten or "readonly" to disallow overwriting. For example:

{
    "globals": {
        "var1": "writable",
        "var2": "readonly"
    }
}

And in YAML:

---
  globals:
    var1: writable
    var2: readonly

These examples allow var1 to be overwritten in your code, but disallow it for var2.

Globals can be disabled with the string "off". For example, in an environment where most ES2015 globals are available but Promise is unavailable, you might use this config:

{
    "env": {
        "es6": true
    },
    "globals": {
        "Promise": "off"
    }
}

For historical reasons, the boolean value false and the string value "readable" are equivalent to "readonly". Similarly, the boolean value true and the string value "writeable" are equivalent to "writable". However, the use of older values is deprecated.

Specifying Parser Options

ESLint allows you to specify the JavaScript language options you want to support. By default, ESLint expects ECMAScript 5 syntax. You can override that setting to enable support for other ECMAScript versions as well as JSX by using parser options.

Please note that supporting JSX syntax is not the same as supporting React. React applies specific semantics to JSX syntax that ESLint doesn't recognize. We recommend using eslint-plugin-react if you are using React and want React semantics. By the same token, supporting ES6 syntax is not the same as supporting new ES6 globals (e.g., new types such as Set). For ES6 syntax, use { "parserOptions": { "ecmaVersion": 6 } }; for new ES6 global variables, use { "env": { "es6": true } }. { "env": { "es6": true } } enables ES6 syntax automatically, but { "parserOptions": { "ecmaVersion": 6 } } does not enable ES6 globals automatically.

Parser options are set in your .eslintrc.* file by using the parserOptions property. The available options are:

  • ecmaVersion - set to 3, 5 (default), 6, 7, 8, 9, 10, 11, 12, or 13 to specify the version of ECMAScript syntax you want to use. You can also set to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), 2019 (same as 10), 2020 (same as 11), 2021 (same as 12), or 2022 (same as 13) to use the year-based naming. You can also set "latest" to use the most recently supported version.
  • sourceType - set to "script" (default) or "module" if your code is in ECMAScript modules.
  • allowReserved - allow the use of reserved words as identifiers (if ecmaVersion is 3).
  • ecmaFeatures - an object indicating which additional language features you'd like to use:
    • globalReturn - allow return statements in the global scope
    • impliedStrict - enable global strict mode (if ecmaVersion is 5 or greater)
    • jsx - enable JSX

Here's an example .eslintrc.json file:

{
    "parserOptions": {
        "ecmaVersion": "latest",
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true
        }
    },
    "rules": {
        "semi": "error"
    }
}

Setting parser options helps ESLint determine what is a parsing error. All language options are false by default.

ads via CarbonAccelerate your Career in Software Development. Apply Now.ads via Carbon

ESLint is designed to be flexible and configurable for your use case. You can turn off every rule and run only with basic syntax validation or mix and match the bundled rules and your custom rules to fit the needs of your project. There are two primary ways to configure ESLint:

  1. Configuration Comments - use JavaScript comments to embed configuration information directly into a file.
  2. Configuration Files - use a JavaScript, JSON, or YAML file to specify configuration information for an entire directory and all of its subdirectories. This can be in the form of a .eslintrc.* file or an eslintConfig field in a package.json file, both of which ESLint will look for and read automatically, or you can specify a configuration file on the command line.

Here are some of the options that you can configure in ESLint:

  • Environments - which environments your script is designed to run in. Each environment brings with it a certain set of predefined global variables.
  • Globals - the additional global variables your script accesses during execution.
  • Rules - which rules are enabled and at what error level.
  • Plugins - which third-party plugins define additional rules, environments, configs, etc. for ESLint to use.

All of these options give you fine-grained control over how ESLint treats your code.

Table of Contents

Configuration Files

Language Options

Rules

Plugins

Ignoring Code

Specifying Parser

By default, ESLint uses Espree as its parser. You can optionally specify that a different parser should be used in your configuration file so long as the parser meets the following requirements:

  1. It must be a Node module loadable from the config file where the parser is used. Usually, this means you should install the parser package separately using npm.
  2. It must conform to the parser interface.

Note that even with these compatibilities, there are no guarantees that an external parser will work correctly with ESLint and ESLint will not fix bugs related to incompatibilities with other parsers.

To indicate the npm module to use as your parser, specify it using the parser option in your .eslintrc file. For example, the following specifies to use Esprima instead of Espree:

{
    "parser": "esprima",
    "rules": {
        "semi": "error"
    }
}

The following parsers are compatible with ESLint:

Note when using a custom parser, the parserOptions configuration property is still required for ESLint to work properly with features not in ECMAScript 5 by default. Parsers are all passed parserOptions and may or may not use them to determine which features to enable.

Specifying Processor

Plugins may provide processors. Processors can extract JavaScript code from other kinds of files, then let ESLint lint the JavaScript code or processors can convert JavaScript code in preprocessing for some purpose.

To specify processors in a configuration file, use the processor key with the concatenated string of a plugin name and a processor name by a slash. For example, the following enables the processor a-processor that the plugin a-plugin provided:

{
    "plugins": ["a-plugin"],
    "processor": "a-plugin/a-processor"
}

To specify processors for specific kinds of files, use the combination of the overrides key and the processor key. For example, the following uses the processor a-plugin/markdown for *.md files.

{
    "plugins": ["a-plugin"],
    "overrides": [
        {
            "files": ["*.md"],
            "processor": "a-plugin/markdown"
        }
    ]
}

Processors may make named code blocks such as 0.js and 1.js. ESLint handles such a named code block as a child file of the original file. You can specify additional configurations for named code blocks in the overrides section of the config. For example, the following disables the strict rule for the named code blocks which end with .js in markdown files.

{
    "plugins": ["a-plugin"],
    "overrides": [
        {
            "files": ["*.md"],
            "processor": "a-plugin/markdown"
        },
        {
            "files": ["**/*.md/*.js"],
            "rules": {
                "strict": "off"
            }
        }
    ]
}

ESLint checks the file path of named code blocks then ignores those if any overrides entry didn't match the file path. Be sure to add an overrides entry if you want to lint named code blocks other than *.js.

Configuring Plugins

ESLint supports the use of third-party plugins. Before using the plugin, you have to install it using npm.

To configure plugins inside of a configuration file, use the plugins key, which contains a list of plugin names. The eslint-plugin- prefix can be omitted from the plugin name.

{
    "plugins": [
        "plugin1",
        "eslint-plugin-plugin2"
    ]
}

And in YAML:

---
  plugins:
    - plugin1
    - eslint-plugin-plugin2

Notes:

  1. Plugins are resolved relative to the config file. In other words, ESLint will load the plugin as a user would obtain by running require('eslint-plugin-pluginname') in the config file.
  2. Plugins in the base configuration (loaded by extends setting) are relative to the derived config file. For example, if ./.eslintrc has extends: ["foo"] and the eslint-config-foo has plugins: ["bar"], ESLint finds the eslint-plugin-bar from ./node_modules/ (rather than ./node_modules/eslint-config-foo/node_modules/) or ancestor directories. Thus every plugin in the config file and base configurations is resolved uniquely.

Naming convention

Include a plugin

The eslint-plugin- prefix can be omitted for non-scoped packages

{
    // ...
    "plugins": [
        "jquery", // means eslint-plugin-jquery
    ]
    // ...
}

The same rule does apply to scoped packages:

{
    // ...
    "plugins": [
        "@jquery/jquery", // means @jquery/eslint-plugin-jquery
        "@foobar" // means @foobar/eslint-plugin
    ]
    // ...
}

Use a plugin

When using rules, environments or configs defined by plugins, they must be referenced following the convention:

  • eslint-plugin-foofoo/a-rule
  • @foo/eslint-plugin@foo/a-config
  • @foo/eslint-plugin-bar@foo/bar/a-environment

For example:

{
    // ...
    "plugins": [
        "jquery",   // eslint-plugin-jquery
        "@foo/foo", // @foo/eslint-plugin-foo
        "@bar"      // @bar/eslint-plugin
    ],
    "extends": [
        "plugin:@foo/foo/recommended",
        "plugin:@bar/recommended"
    ],
    "rules": {
        "jquery/a-rule": "error",
        "@foo/foo/some-rule": "error",
        "@bar/another-rule": "error"
    },
    "env": {
        "jquery/jquery": true,
        "@foo/foo/env-foo": true,
        "@bar/env-bar": true,
    }
    // ...
}

Configuring Rules

ESLint comes with a large number of built-in rules and you can add more rules through plugins. You can modify which rules your project uses either using configuration comments or configuration files. To change a rule setting, you must set the rule ID equal to one of these values:

  • "off" or 0 - turn the rule off
  • "warn" or 1 - turn the rule on as a warning (doesn't affect exit code)
  • "error" or 2 - turn the rule on as an error (exit code is 1 when triggered)

To configure rules inside of a file using configuration comments, use a comment in the following format:

/* eslint eqeqeq: "off", curly: "error" */

In this example, eqeqeq is turned off and curly is turned on as an error. You can also use the numeric equivalent for the rule severity:

/* eslint eqeqeq: 0, curly: 2 */

This example is the same as the last example, only it uses the numeric codes instead of the string values. The eqeqeq rule is off and the curly rule is set to be an error.

If a rule has additional options, you can specify them using array literal syntax, such as:

/* eslint quotes: ["error", "double"], curly: 2 */

This comment specifies the "double" option for the quotes rule. The first item in the array is always the rule severity (number or string).

Configuration comments can include descriptions to explain why the comment is necessary. The description must occur after the configuration and is separated from the configuration by two or more consecutive - characters. For example:

/* eslint eqeqeq: "off", curly: "error" -- Here's a description about why this configuration is necessary. */
/* eslint eqeqeq: "off", curly: "error"
    --------
    Here's a description about why this configuration is necessary. */
/* eslint eqeqeq: "off", curly: "error"
 * --------
 * This will not work due to the line above starting with a '*' character.
 */

Using configuration files

To configure rules inside of a configuration file, use the rules key along with an error level and any options you want to use. For example:

{
    "rules": {
        "eqeqeq": "off",
        "curly": "error",
        "quotes": ["error", "double"]
    }
}

And in YAML:

---
rules:
  eqeqeq: off
  curly: error
  quotes:
    - error
    - double

To configure a rule which is defined within a plugin you have to prefix the rule ID with the plugin name and a /. For example:

{
    "plugins": [
        "plugin1"
    ],
    "rules": {
        "eqeqeq": "off",
        "curly": "error",
        "quotes": ["error", "double"],
        "plugin1/rule1": "error"
    }
}

And in YAML:

---
plugins:
  - plugin1
rules:
  eqeqeq: 0
  curly: error
  quotes:
    - error
    - "double"
  plugin1/rule1: error

In these configuration files, the rule plugin1/rule1 comes from the plugin named plugin1. You can also use this format with configuration comments, such as:

/* eslint "plugin1/rule1": "error" */

Note: When specifying rules from plugins, make sure to omit eslint-plugin-. ESLint uses only the unprefixed name internally to locate rules.

Disabling Rules

To temporarily disable rule warnings in your file, use block comments in the following format:

/* eslint-disable */

alert('foo');

/* eslint-enable */

You can also disable or enable warnings for specific rules:

/* eslint-disable no-alert, no-console */

alert('foo');
console.log('bar');

/* eslint-enable no-alert, no-console */

Note: /* eslint-enable */ without any specific rules listed will cause all disabled rules to be re-enabled.

To disable rule warnings in an entire file, put a /* eslint-disable */ block comment at the top of the file:

/* eslint-disable */

alert('foo');

You can also disable or enable specific rules for an entire file:

/* eslint-disable no-alert */

alert('foo');

To ensure that a rule is never applied (regardless of any future enable/disable lines):

/* eslint no-alert: "off" */

alert('foo');

To disable all rules on a specific line, use a line or block comment in one of the following formats:

alert('foo'); // eslint-disable-line

// eslint-disable-next-line
alert('foo');

/* eslint-disable-next-line */
alert('foo');

alert('foo'); /* eslint-disable-line */

To disable a specific rule on a specific line:

alert('foo'); // eslint-disable-line no-alert

// eslint-disable-next-line no-alert
alert('foo');

alert('foo'); /* eslint-disable-line no-alert */

/* eslint-disable-next-line no-alert */
alert('foo');

To disable multiple rules on a specific line:

alert('foo'); // eslint-disable-line no-alert, quotes, semi

// eslint-disable-next-line no-alert, quotes, semi
alert('foo');

alert('foo'); /* eslint-disable-line no-alert, quotes, semi */

/* eslint-disable-next-line no-alert, quotes, semi */
alert('foo');

/* eslint-disable-next-line 
  no-alert, 
  quotes, 
  semi 
*/
alert('foo');

All of the above methods also work for plugin rules. For example, to disable eslint-plugin-example's rule-name rule, combine the plugin's name (example) and the rule's name (rule-name) into example/rule-name:

foo(); // eslint-disable-line example/rule-name
foo(); /* eslint-disable-line example/rule-name */

Configuration comments can include descriptions to explain why the comment is necessary. The description must come after the configuration and needs to be separated from the configuration by two or more consecutive - characters. For example:

// eslint-disable-next-line no-console -- Here's a description about why this configuration is necessary.
console.log('hello');

/* eslint-disable-next-line no-console --
 * Here's a very long description about why this configuration is necessary
 * along with some additional information
**/
console.log('hello');

Note: Comments that disable warnings for a portion of a file tell ESLint not to report rule violations for the disabled code. ESLint still parses the entire file, however, so disabled code still needs to be syntactically valid JavaScript.

Using configuration files

To disable rules inside of a configuration file for a group of files, use the overrides key along with a files key. For example:

{
  "rules": {...},
  "overrides": [
    {
      "files": ["*-test.js","*.spec.js"],
      "rules": {
        "no-unused-expressions": "off"
      }
    }
  ]
}

To disable all inline config comments, use the noInlineConfig setting. For example:

{
  "rules": {...},
  "noInlineConfig": true
}

This setting is similar to --no-inline-config CLI option.

To report unused eslint-disable comments, use the reportUnusedDisableDirectives setting. For example:

{
  "rules": {...},
  "reportUnusedDisableDirectives": true
}

This setting is similar to --report-unused-disable-directives CLI option, but doesn't fail linting (reports as "warn" severity).

Url: https://eslint.org/docs/user-guide/configuring/rules#configuring-rules

Configuring Rules

ESLint comes with a large number of built-in rules and you can add more rules through plugins. You can modify which rules your project uses either using configuration comments or configuration files. To change a rule setting, you must set the rule ID equal to one of these values:

  • "off" or 0 - turn the rule off
  • "warn" or 1 - turn the rule on as a warning (doesn't affect exit code)
  • "error" or 2 - turn the rule on as an error (exit code is 1 when triggered)

To configure rules inside of a file using configuration comments, use a comment in the following format:

/* eslint eqeqeq: "off", curly: "error" */

In this example, eqeqeq is turned off and curly is turned on as an error. You can also use the numeric equivalent for the rule severity:

/* eslint eqeqeq: 0, curly: 2 */

This example is the same as the last example, only it uses the numeric codes instead of the string values. The eqeqeq rule is off and the curly rule is set to be an error.

If a rule has additional options, you can specify them using array literal syntax, such as:

/* eslint quotes: ["error", "double"], curly: 2 */

This comment specifies the "double" option for the quotes rule. The first item in the array is always the rule severity (number or string).

Configuration comments can include descriptions to explain why the comment is necessary. The description must occur after the configuration and is separated from the configuration by two or more consecutive - characters. For example:

/* eslint eqeqeq: "off", curly: "error" -- Here's a description about why this configuration is necessary. */
/* eslint eqeqeq: "off", curly: "error"
    --------
    Here's a description about why this configuration is necessary. */
/* eslint eqeqeq: "off", curly: "error"
 * --------
 * This will not work due to the line above starting with a '*' character.
 */

Using configuration files

To configure rules inside of a configuration file, use the rules key along with an error level and any options you want to use. For example:

{
    "rules": {
        "eqeqeq": "off",
        "curly": "error",
        "quotes": ["error", "double"]
    }
}

And in YAML:

---
rules:
  eqeqeq: off
  curly: error
  quotes:
    - error
    - double

To configure a rule which is defined within a plugin you have to prefix the rule ID with the plugin name and a /. For example:

{
    "plugins": [
        "plugin1"
    ],
    "rules": {
        "eqeqeq": "off",
        "curly": "error",
        "quotes": ["error", "double"],
        "plugin1/rule1": "error"
    }
}

And in YAML:

---
plugins:
  - plugin1
rules:
  eqeqeq: 0
  curly: error
  quotes:
    - error
    - "double"
  plugin1/rule1: error

In these configuration files, the rule plugin1/rule1 comes from the plugin named plugin1. You can also use this format with configuration comments, such as:

/* eslint "plugin1/rule1": "error" */

Note: When specifying rules from plugins, make sure to omit eslint-plugin-. ESLint uses only the unprefixed name internally to locate rules.

Disabling Rules

To temporarily disable rule warnings in your file, use block comments in the following format:

/* eslint-disable */

alert('foo');

/* eslint-enable */

You can also disable or enable warnings for specific rules:

/* eslint-disable no-alert, no-console */

alert('foo');
console.log('bar');

/* eslint-enable no-alert, no-console */

Note: /* eslint-enable */ without any specific rules listed will cause all disabled rules to be re-enabled.

To disable rule warnings in an entire file, put a /* eslint-disable */ block comment at the top of the file:

/* eslint-disable */

alert('foo');

You can also disable or enable specific rules for an entire file:

/* eslint-disable no-alert */

alert('foo');

To ensure that a rule is never applied (regardless of any future enable/disable lines):

/* eslint no-alert: "off" */

alert('foo');

To disable all rules on a specific line, use a line or block comment in one of the following formats:

alert('foo'); // eslint-disable-line

// eslint-disable-next-line
alert('foo');

/* eslint-disable-next-line */
alert('foo');

alert('foo'); /* eslint-disable-line */

To disable a specific rule on a specific line:

alert('foo'); // eslint-disable-line no-alert

// eslint-disable-next-line no-alert
alert('foo');

alert('foo'); /* eslint-disable-line no-alert */

/* eslint-disable-next-line no-alert */
alert('foo');

To disable multiple rules on a specific line:

alert('foo'); // eslint-disable-line no-alert, quotes, semi

// eslint-disable-next-line no-alert, quotes, semi
alert('foo');

alert('foo'); /* eslint-disable-line no-alert, quotes, semi */

/* eslint-disable-next-line no-alert, quotes, semi */
alert('foo');

/* eslint-disable-next-line 
  no-alert, 
  quotes, 
  semi 
*/
alert('foo');

All of the above methods also work for plugin rules. For example, to disable eslint-plugin-example's rule-name rule, combine the plugin's name (example) and the rule's name (rule-name) into example/rule-name:

foo(); // eslint-disable-line example/rule-name
foo(); /* eslint-disable-line example/rule-name */

Configuration comments can include descriptions to explain why the comment is necessary. The description must come after the configuration and needs to be separated from the configuration by two or more consecutive - characters. For example:

// eslint-disable-next-line no-console -- Here's a description about why this configuration is necessary.
console.log('hello');

/* eslint-disable-next-line no-console --
 * Here's a very long description about why this configuration is necessary
 * along with some additional information
**/
console.log('hello');

Note: Comments that disable warnings for a portion of a file tell ESLint not to report rule violations for the disabled code. ESLint still parses the entire file, however, so disabled code still needs to be syntactically valid JavaScript.

Using configuration files

To disable rules inside of a configuration file for a group of files, use the overrides key along with a files key. For example:

{
  "rules": {...},
  "overrides": [
    {
      "files": ["*-test.js","*.spec.js"],
      "rules": {
        "no-unused-expressions": "off"
      }
    }
  ]
}

To disable all inline config comments, use the noInlineConfig setting. For example:

{
  "rules": {...},
  "noInlineConfig": true
}

This setting is similar to --no-inline-config CLI option.

To report unused eslint-disable comments, use the reportUnusedDisableDirectives setting. For example:

{
  "rules": {...},
  "reportUnusedDisableDirectives": true
}

This setting is similar to --report-unused-disable-directives CLI option, but doesn't fail linting (reports as "warn" severity).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment