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.

Tokens
6.9K
Snippets
40
Records
57
Agent score
72%

What's inside Learn ESLint

  1. Introduction to ESLint for JavaScript and JSX

    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.
  2. Understand the difference between ESLint Config and ESLint Plugin

    ESLint uses two different mechanisms for sharing and extending linting logic:

    1. 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:recommended is a shared configuration that provides a baseline of standard rules.
    2. 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.
  3. 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.
  4. 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 the plugin/rule format.
    /* 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-name
  5. Implement auto-fixing for custom ESLint rules

    To enable automatic fixing for a custom ESLint rule, you must perform three key steps:

    1. Add the fixable property to the meta object of the rule definition to indicate that the rule supports automatic fixes.
    2. Capture the relevant AST node (e.g., a CallExpression for outdated function calls) within the rule's visitor function.
    3. Use the ESLint fixer API provided in the context.report callback to define how the code should be transformed.

    Once implemented, these errors can be automatically resolved by running ESLint with the --fix flag.

    # Run ESLint with the fix flag to automatically apply the custom rule's fixes
    eslint --fix
  6. Configure ESLint using comments or files

    ESLint provides two primary methods for configuration to allow flexible control over code linting:

    1. Configuration Comments: Embed configuration information directly within JavaScript files using comments.
    2. Configuration Files: Use dedicated JavaScript, JSON, or YAML files (e.g., .eslintrc.*) or an eslintConfig field in package.json to specify configuration for an entire directory and its subdirectories. ESLint automatically detects these files or reads the configuration specified via the command line.
  7. 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 the context API to inspect source code comments. The implementation involves using context.getSourceCode() to access the current file being parsed and sourceCode.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.'
                });
              }
            });
          }
        };
      }
    };
  8. 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:

    1. 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.
    2. Configuration Export: Create an index.js file in the root of the package and export the ESLint configuration object from it.
    3. Usage in Other Projects: To use the shared configuration in a target project, install the package and add it to the extends array in the .eslintrc file. When referencing the package in extends, omit the eslint-config- prefix and only provide the xxx part 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"
    }
  9. 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 the eslintConfig field of a package.json file or specified via the command line during execution.