Learn ESLint Guide
website·Indexed 29 days ago
https://sudongyuer.github.io/learn-eslint/A comprehensive guide to ESLint, covering installation, configuration, and usage in React projects. The documentation includes detailed instructions on creating custom rules and plugins, understanding Abstract Syntax Trees (AST), integrating ESLint with editors like VS Code and WebStorm, and managing shared configurations and plugins.
What's inside Learn ESLint
- ESLint is an open-source static analysis tool used to find and fix problems in JavaScript and JSX code. It works across different environments (browser or server) and regardless of whether a framework is used. It can be integrated directly into most text editors or run as part of a Continuous Integration (CI) pipeline.
Understand the difference between ESLint Config and ESLint Plugin
ESLint uses two different mechanisms for sharing and extending linting logic:
- ESLint Config: A JavaScript object containing a set of configuration options. It is used to share a predefined set of rules and environment settings across projects. For example,
eslint:recommendedis a shared configuration that provides a baseline of standard rules. - ESLint Plugin: A collection of custom rules (and optionally configuration files) that can be imported and used. While a config shares settings, a plugin provides the actual logic for new, custom rules that ESLint does not have built-in.
- ESLint Config: A JavaScript object containing a set of configuration options. It is used to share a predefined set of rules and environment settings across projects. For example,
Understand Abstract Syntax Trees (AST) for JavaScript
An Abstract Syntax Tree (AST) is a simplified version of a parse tree (also known as a Concrete Syntax Tree or CST). While a parse tree contains all syntactic information of the code, an AST strips away unimportant details to provide a tree-like object representation of the source code. In essence, an AST uses JavaScript objects to describe the structure of code, allowing tools to analyze and transform it programmatically.Integrate ESLint in WebStorm
WebStorm comes with built-in ESLint integration, so no separate plugin installation is required. To enable automatic linting fixes, navigate to the WebStorm settings/preferences and configure the ESLint auto-fix option.Disable ESLint rules for specific lines or blocks
ESLint provides several ways to temporarily disable rules using comments. You can disable all rules or specific rules for a block of code, a single line, or the next line. Plugin rules are disabled using theplugin/ruleformat./* eslint-disable */ alert('foo'); // All rules disabled /* eslint-enable */ /* eslint-disable no-alert */ alert('bar'); // Only no-alert disabled for the rest of the file alert('baz'); // eslint-disable-line no-alert // eslint-disable-next-line no-alert, quotes alert('qux'); foo(); // eslint-disable-line example/rule-nameImplement auto-fixing for custom ESLint rules
To enable automatic fixing for a custom ESLint rule, you must perform three key steps:
- Add the
fixableproperty to themetaobject of the rule definition to indicate that the rule supports automatic fixes. - Capture the relevant AST node (e.g., a
CallExpressionfor outdated function calls) within the rule's visitor function. - Use the ESLint
fixerAPI provided in thecontext.reportcallback to define how the code should be transformed.
Once implemented, these errors can be automatically resolved by running ESLint with the
--fixflag.# Run ESLint with the fix flag to automatically apply the custom rule's fixes eslint --fix- Add the
Configure ESLint using comments or files
ESLint provides two primary methods for configuration to allow flexible control over code linting:
- Configuration Comments: Embed configuration information directly within JavaScript files using comments.
- Configuration Files: Use dedicated JavaScript, JSON, or YAML files (e.g.,
.eslintrc.*) or aneslintConfigfield inpackage.jsonto specify configuration for an entire directory and its subdirectories. ESLint automatically detects these files or reads the configuration specified via the command line.
Use an ESLint Config to share rule sets
An ESLint Config is used to apply a group of shared rules to a project. When a shared config (likeeslint:recommended) is loaded, ESLint applies all rules defined in that config. Developers can then add or override specific rules in therulessection of their own local configuration to customize the behavior.Create a custom ESLint rule to find TODO comments
To identify TODO comments in a project, you can create a custom ESLint rule that leverages thecontextAPI to inspect source code comments. The implementation involves usingcontext.getSourceCode()to access the current file being parsed andsourceCode.getAllComments()to retrieve all comments within that file to check for the 'TODO' string.// Example logic for the custom rule module.exports = { create(context) { return { Program() { const sourceCode = context.getSourceCode(); const comments = sourceCode.getAllComments(); comments.forEach(comment => { if (comment.value.includes('TODO')) { context.report({ node: comment, message: 'Found a TODO comment that needs to be addressed.' }); } }); } }; } };Use an ESLint Plugin to implement custom rules
ESLint Plugins are used when you need to introduce custom linting rules that are not part of the ESLint core. A plugin is typically imported fromnode_modules(e.g.,eslint-plugin-react). Once the plugin is loaded, you can specify and enable the custom rules exported by that plugin within your ESLint configuration.Create and publish a shareable ESLint configuration
To create a shareable ESLint configuration that can be published to npm and used by other projects, follow these requirements:
- Naming Convention: The npm package name must follow the pattern
eslint-config-xxx(e.g.,eslint-config-my-company). This is a strict ESLint convention required for the configuration to be recognized. - Configuration Export: Create an
index.jsfile in the root of the package and export the ESLint configuration object from it. - Usage in Other Projects: To use the shared configuration in a target project, install the package and add it to the
extendsarray in the.eslintrcfile. When referencing the package inextends, omit theeslint-config-prefix and only provide thexxxpart of the name.
// In the shareable config package: index.js module.exports = { rules: { 'no-console': 'warn', 'semi': ['error', 'always'], // other rules } };// In the consuming project: .eslintrc { "extends": "xxx" }- Naming Convention: The npm package name must follow the pattern
Configure ESLint using files or comments
ESLint can be configured in two primary ways: by embedding configuration information directly into source files using JavaScript comments, or by using a configuration file for a directory and its subdirectories. Supported configuration file formats include JavaScript, JSON, or YAML (e.g.,.eslintrc.*). Alternatively, configuration can be defined in theeslintConfigfield of apackage.jsonfile or specified via the command line during execution.