### Example Conventional Commit Summaries (Git) Source: https://zh-hans.eslint.org/docs/latest/contribute/pull-requests These are examples of valid commit message summaries in ESLint, demonstrating the use of tags like 'build', 'fix', and 'chore' followed by a concise description. ```git build: Update Travis to only test Node 0.10 fix: Semi rule incorrectly flagging extra semicolon chore: Upgrade Esprima to 1.2, switch to using comment attachment ``` -------------------------------- ### Basic 'Hello World' Example (JavaScript) Source: https://zh-hans.eslint.org/docs/latest/extend/code-path-analysis A simple 'Hello World' program demonstrating basic JavaScript execution. This snippet is often used as a starting point for testing or illustrating simple console output. ```javascript console.log("Hello world!"); ``` -------------------------------- ### Correct Examples: Handling Multiline Expressions (JavaScript) Source: https://zh-hans.eslint.org/docs/latest/rules/no-unexpected-multiline Illustrates correct code patterns that adhere to the 'no-unexpected-multiline' rule. These examples show how to properly terminate statements or use specific keywords to avoid misinterpretation by ASI. ```javascript /*eslint no-unexpected-multiline: "error"*/ var foo = bar; (1 || 2).baz(); var foo = bar ;(1 || 2).baz() var hello = 'world'; [1, 2, 3].forEach(addNumber); var hello = 'world' void [1, 2, 3].forEach(addNumber); let x = function() {}; `hello` let tag = function() {} tag `hello` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ``` -------------------------------- ### ESLint Configuration: Enabling Recommended Rules (JSON) Source: https://zh-hans.eslint.org/docs/latest/use/migrating-to-1 This JSON configuration enables the recommended set of ESLint rules, which mimics some of the default behaviors from ESLint v0.x. It's a common pattern for projects starting with ESLint or migrating to v1.0.0. ```json { "extends": "eslint:recommended" } ``` -------------------------------- ### Using New RuleTester for ESLint Rules Source: https://zh-hans.eslint.org/docs/latest/use/migrating-to-1 This snippet shows the modern approach to testing ESLint rules using the RuleTester class, now integrated into the 'eslint' module. It simplifies the setup by directly requiring 'eslint' and instantiating RuleTester without needing the eslint instance. ```javascript var rule = require("../../../lib/rules/your-rule"), RuleTester = require("eslint").RuleTester; var ruleTester = new RuleTester(); ruleTester.run("your-rule", rule, { valid: [], invalid: [] }); ``` -------------------------------- ### Object Curly Spacing: 'arraysInObjects' Option Examples (JavaScript) Source: https://zh-hans.eslint.org/docs/latest/rules/object-curly-spacing Demonstrates the effect of the 'arraysInObjects' option when combined with 'never' or 'always'. This option controls spacing for objects that start or end with array elements. ```javascript /*eslint object-curly-spacing: ["error", "never", { "arraysInObjects": true }]*/ // Correct with 'never' and arraysInObjects: true var obj = {"foo": [ 1, 2 ] }; var obj = {"foo": [ "baz", "bar" ] }; /*eslint object-curly-spacing: ["error", "always", { "arraysInObjects": false }]*/ // Correct with 'always' and arraysInObjects: false var obj = { "foo": [ 1, 2 ]}; var obj = { "foo": [ "baz", "bar" ]}; ``` -------------------------------- ### 创建 ESLint 配置文件 Source: https://zh-hans.eslint.org/docs/latest/use/getting-started 使用 touch 命令创建一个空的 JavaScript 配置文件(.eslintrc.js)以供 ESLint 使用。此文件将用于手动配置 ESLint 规则、环境等。 ```bash # 创建 JavaScript 配置文件 touch .eslintrc.js ``` -------------------------------- ### ESLint: Correct usage with decoration characters (JavaScript) Source: https://zh-hans.eslint.org/docs/latest/rules/no-warning-comments This example demonstrates the correct usage of the no-warning-comments rule when specific decoration characters are configured to be ignored. It shows that comments starting with non-decoration characters after the ignored prefixes will still be flagged if they contain warning terms. ```javascript /*eslint no-warning-comments: ["error", { "decoration": ["/", "*"] }]*/ //!TODO preceded by non-decoration character /** *!TODO preceded by non-decoration character in a block comment */ ``` -------------------------------- ### 安装和配置 ESLint Source: https://zh-hans.eslint.org/docs/latest/use/getting-started 使用 npm 命令安装并配置 ESLint。此命令会在项目中创建一个 ESLint 配置文件,并根据提示进行设置。前提是项目中已存在 package.json 文件。 ```bash npm init @eslint/config ``` ```bash # 使用 semistandard 可共享配置 npm init @eslint/config -- --config semistandard # 或 npm init @eslint/config -- --config eslint-config-semistandard # 使用多个可共享配置 npm init @eslint/config -- --config semistandard,standard # 或 npm init @eslint/config -- --config semistandard --config standard ``` -------------------------------- ### ESLint: Example with `ignorePattern` Source: https://zh-hans.eslint.org/docs/latest/rules/capitalized-comments This example demonstrates the `ignorePattern` option, where a comment starting with 'pragma' is correctly handled even when the rule requires capitalized comments. ```javascript /* eslint capitalized-comments: ["error", "always", { "ignorePattern": "pragma" }] */ function foo() { /* pragma wrap(true) */ } ``` -------------------------------- ### 使用 ESLint 检查文件 Source: https://zh-hans.eslint.org/docs/latest/use/getting-started 在安装和配置 ESLint 后,可以使用 npx 或 yarn 命令来检查指定的 JavaScript 文件或目录。确保已在本地安装 ESLint。 ```bash npx eslint yourfile.js ``` ```bash yarn run eslint yourfile.js ``` ```bash npx eslint project-dir/ file1.js ``` -------------------------------- ### ESLint: Example of Incorrect Comment ('never') Source: https://zh-hans.eslint.org/docs/latest/rules/capitalized-comments This example shows an error flagged by the `capitalized-comments` rule when configured to 'never' capitalize comments, and a comment starts with an uppercase letter. ```javascript /* eslint capitalized-comments: ["error", "never"] */ // Capitalized comment ``` -------------------------------- ### JavaScript 扩展 eslint:recommended 配置 Source: https://zh-hans.eslint.org/docs/latest/use/configure/configuration-files 使用 JavaScript 模块格式扩展 ESLint 的推荐配置 (`eslint:recommended`),并覆盖或添加特定规则。适用于希望快速应用 ESLint 核心规则并进行少量定制的项目。 ```javascript module.exports = { "extends": "eslint:recommended", "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"], // 禁用基础配置汇总的规则 "for-direction": "off", } } ``` -------------------------------- ### ESLint: Example with `ignoreInlineComments` Source: https://zh-hans.eslint.org/docs/latest/rules/capitalized-comments This example shows how `ignoreInlineComments: true` allows inline comments like `/* ignored */` to pass the `capitalized-comments` rule, even if they don't start with a capital letter. ```javascript /* eslint capitalized-comments: ["error", "always", { "ignoreInlineComments": true }] */ function foo(/* ignored */ a) { } ``` -------------------------------- ### Initialize ESLint Configuration (`--init`) Source: https://zh-hans.eslint.org/docs/latest/use/command-line-interface Runs the `npm init @eslint/config` wizard to create an `.eslintrc` file. This command does not perform checks when the flag is used. It's designed for new users to quickly set up their configuration. ```bash npx eslint --init ``` -------------------------------- ### ESLint: Example of Incorrect Comment (Default) Source: https://zh-hans.eslint.org/docs/latest/rules/capitalized-comments This example demonstrates an error flagged by the `capitalized-comments` rule when it's configured to 'always' capitalize comments, and an inline comment starts with a lowercase letter. ```javascript /* eslint capitalized-comments: ["error"] */ // lowercase comment ``` -------------------------------- ### ESLint: Example of Correct Comments ('never') Source: https://zh-hans.eslint.org/docs/latest/rules/capitalized-comments This example shows comments that adhere to the `capitalized-comments` rule when configured to 'never' capitalize. It includes correctly lowercased comments and comments starting with non-letters or non-Latin characters. ```javascript // 小写注释 // 1. 非字母开头的注释 // 丈 非拉丁字符开头的注释 ``` -------------------------------- ### ESLint: Example of Correct Comments (Default) Source: https://zh-hans.eslint.org/docs/latest/rules/capitalized-comments This example shows comments that adhere to the `capitalized-comments` rule when configured to 'always' capitalize. It includes correctly capitalized comments, comments starting with non-letters, and non-Latin characters. ```javascript // Capitalized comment // 1. Non-letter at beginning of comment // 丈 Non-Latin character at beginning of comment ``` -------------------------------- ### ESLint CLI 命令行配置 Source: https://zh-hans.eslint.org/docs/latest/use/configure/configuration-files 使用 `--config` 选项通过命令行指定 ESLint 配置文件。这允许你为特定的文件或目录使用自定义配置,而无需将其保存在项目目录中。ESLint 会忽略所有 `.eslintrc.*` 文件,除非同时使用了 `--config` 标志。 ```bash eslint -c myconfig.json myfiletotest.js ``` -------------------------------- ### Display Help Menu (`-h`, `--help`) Source: https://zh-hans.eslint.org/docs/latest/use/command-line-interface Outputs the help menu and displays all available options. If this option is present, all other options are ignored. The command-line does not perform checks when this flag is used. ```bash npx eslint --help ``` -------------------------------- ### Allow block comments at start of blocks (ESLint) Source: https://zh-hans.eslint.org/docs/latest/rules/lines-around-comment This example shows the ESLint configuration for 'lines-around-comment' with `allowBlockStart: true`, permitting block comments at the beginning of code blocks without a preceding empty line. It includes correct code examples. ```javascript /*eslint lines-around-comment: ["error", { "beforeBlockComment": true, "allowBlockStart": true }]*/ function foo(){ /* what a great and wonderful day */ var day = "great" return day; } if (bar) { /* what a great and wonderful day */ foo(); } class C { /* what a great and wonderful day */ method() { /* what a great and wonderful day */ foo(); } static { /* what a great and wonderful day */ foo(); } } switch (foo) { /* what a great and wonderful day */ case 1: bar(); break; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 ``` -------------------------------- ### 构建浏览器版本的 ESLint Source: https://zh-hans.eslint.org/docs/latest/contribute/development-environment 使用 `npm run webpack` 命令生成 `build/eslint.js` 文件,这是用于在浏览器环境中使用的 ESLint 版本。 ```bash npm run webpack ``` -------------------------------- ### Allow line comments at start of blocks (ESLint) Source: https://zh-hans.eslint.org/docs/latest/rules/lines-around-comment This example demonstrates ESLint configuration for 'lines-around-comment' with `allowBlockStart: true`, allowing line comments at the beginning of blocks without requiring a preceding empty line. It shows correct code examples. ```javascript /*eslint lines-around-comment: ["error", { "beforeLineComment": true, "allowBlockStart": true }]*/ function foo(){ // what a great and wonderful day var day = "great" return day; } if (bar) { // what a great and wonderful day foo(); } class C { // what a great and wonderful day method() { // what a great and wonderful day foo(); } static { // what a great and wonderful day foo(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ``` -------------------------------- ### YAML 扩展 ESLint 配置 Source: https://zh-hans.eslint.org/docs/latest/use/configure/configuration-files 使用 YAML 格式扩展 ESLint 配置,继承 'standard' 配置并自定义规则。适用于需要简化 ESLint 配置的项目。 ```yaml extends: standard rules: comma-dangle: - error - always no-empty: warn ``` -------------------------------- ### JavaScript 扩展 eslint:all 配置 Source: https://zh-hans.eslint.org/docs/latest/use/configure/configuration-files 使用 JavaScript 模块格式扩展 ESLint 的所有核心规则 (`eslint:all`),并选择性地覆盖或禁用某些规则。适用于在项目初期探索所有规则或在受控环境下使用(不推荐用于生产)。 ```javascript module.exports = { "extends": "eslint:all", "rules": { // 覆盖默认选项 "comma-dangle": ["error", "always"], "indent": ["error", 2], "no-cond-assign": ["error", "always"], // 当前禁用,但未来可能会启用 "one-var": "off", // ["error", "never"] // 禁用 "init-declarations": "off", "no-console": "off", "no-inline-comments": "off", } } ``` -------------------------------- ### YAML 配置文件中的共享设置 Source: https://zh-hans.eslint.org/docs/latest/use/configure/configuration-files-new 在 YAML 格式的 ESLint 配置文件中定义 `settings` 对象,用于在所有规则之间共享信息。这使得自定义规则能够访问配置好的通用数据。 ```yaml --- settings: sharedData: "Hello" ``` -------------------------------- ### ESLint spaced-line-comment Rule: Correct Example ('never') Source: https://zh-hans.eslint.org/docs/latest/rules/spaced-line-comment This is a correct usage example for the 'never' option of the spaced-line-comment rule, showing a line comment without any whitespace after the '//'. This configuration prioritizes minimizing comment code. ```javascript //When ["never"] //This is a comment with no whitespace at the beginning var foo = 5; 1 2 3 ``` -------------------------------- ### Error Examples: Unexpected Multiline Expressions (JavaScript) Source: https://zh-hans.eslint.org/docs/latest/rules/no-unexpected-multiline Demonstrates code patterns that violate the 'no-unexpected-multiline' rule. These examples show where a newline incorrectly suggests a statement end, leading to parsing issues with Automatic Semicolon Insertion. ```javascript /*eslint no-unexpected-multiline: "error"*/ var foo = bar (1 || 2).baz(); var hello = 'world' [1, 2, 3].forEach(addNumber); let x = function() {} `hello` let y = function() {} y `hello` let z = foo /regex/g.test(bar) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ``` -------------------------------- ### ESLint YAML 配置文件设置根目录 Source: https://zh-hans.eslint.org/docs/latest/use/configure/configuration-files 在 ESLint YAML 配置文件中设置 `root: true`,以指示 ESLint 在此目录停止向上搜索配置文件。这有助于限制 ESLint 的作用范围到特定的项目。 ```yaml --- root: true ``` -------------------------------- ### Yoda Conditions: Disallow Yoda Style (never) - Correct Examples Source: https://zh-hans.eslint.org/docs/latest/rules/yoda Shows correct conditional statements when the 'never' option is active, demonstrating standard variable-first comparisons. This includes examples with string, template literal, and bitwise operations. ```javascript /*eslint yoda: "error"*/ if (5 & value) { // ... } if (value === "red") { // ... } if (value === `red`) { // ... } if (`${value}` === `red`) { } ``` -------------------------------- ### Object Shorthand Syntax Examples (ES5 vs ES6) Source: https://zh-hans.eslint.org/docs/latest/rules/object-shorthand Demonstrates the difference between ES5 and ES6 syntax for object literals, highlighting the conciseness of ES6 object shorthand for properties and methods. ```javascript // properties var foo = { x: x, y: y, z: z, }; // methods var foo = { a: function() {}, b: function() {} }; ``` ```javascript /*eslint-env es6*/ // properties var foo = {x, y, z}; // methods var foo = { a() {}, b() {} }; ``` -------------------------------- ### ESLint spaced-line-comment Rule: Correct Example ('always') Source: https://zh-hans.eslint.org/docs/latest/rules/spaced-line-comment This is a correct usage example for the 'always' option of the spaced-line-comment rule, demonstrating a line comment with proper spacing after the '//'. This ensures readability as per the rule's intention. ```javascript // When ["always"] // This is a comment with a whitespace at the beginning var foo = 5; 1 2 3 ``` -------------------------------- ### ESLint YAML 配置文件中的共享设置 Source: https://zh-hans.eslint.org/docs/latest/use/configure/configuration-files 如何在 ESLint 的 YAML 配置文件中定义 `settings` 部分,以便在所有规则中共享数据。这对于自定义规则访问通用配置信息非常有用。 ```yaml --- settings: sharedData: "Hello" ``` -------------------------------- ### Error Example: Redeclaring Built-in Globals (JavaScript) Source: https://zh-hans.eslint.org/docs/latest/rules/no-redeclare This example shows an error when the 'no-redeclare' rule is configured with 'builtinGlobals: true' and a built-in global like 'Object' is redeclared. This helps prevent accidental overwriting of essential JavaScript objects. ```javascript /*eslint no-redeclare: ["error", { "builtinGlobals": true }]*/ var Object = 0; ``` -------------------------------- ### 传递多个值给 ESLint 选项 Source: https://zh-hans.eslint.org/docs/latest/use/command-line-interface 某些 ESLint 选项支持通过重复选项或提供逗号分隔的列表来传递多个值。这对于配置文件扩展名或忽略模式非常有用。请注意,`--ignore-pattern` 选项不支持列表格式。 ```bash # 使用重复的 --ext 选项 npx eslint --ext .jsx --ext .js lib/ # 使用逗号分隔的列表 npx eslint --ext .jsx,.js lib/ ``` -------------------------------- ### ESLint rule template-curly-spacing: 'always' option example (JavaScript) Source: https://zh-hans.eslint.org/docs/latest/rules/template-curly-spacing This example demonstrates incorrect code when using the 'always' option for the 'template-curly-spacing' rule. It shows cases where spaces are missing inside the curly braces of template string expressions, which are flagged as errors. ```javascript /*eslint template-curly-spacing: ["error", "always"]*/ `hello, ${ people.name}!`; `hello, ${people.name }!`; `hello, ${people.name}!`; ``` -------------------------------- ### ESLint rule template-curly-spacing: 'never' option example (JavaScript) Source: https://zh-hans.eslint.org/docs/latest/rules/template-curly-spacing This example demonstrates incorrect code when using the 'never' option for the 'template-curly-spacing' rule. It shows cases where spaces are present inside the curly braces of template string expressions, which are flagged as errors. ```javascript /*eslint template-curly-spacing: "error"*/ `hello, ${ people.name}!`; `hello, ${people.name }!`; `hello, ${ people.name }!`; ``` -------------------------------- ### ESLint: 强制启用/禁用颜色 (`--color`, `--no-color`) Source: https://zh-hans.eslint.org/docs/latest/use/command-line-interface 可以使用 `--color` 选项强制启用颜色渲染,或使用 `--no-color` 选项强制禁用颜色渲染。这允许您覆盖 ESLint 的默认颜色行为,例如在管道输出时。 ```bash npx eslint --color file.js | cat npx eslint --no-color file.js ``` -------------------------------- ### 手动安装 ESLint Source: https://zh-hans.eslint.org/docs/latest/use/getting-started 手动将 ESLint 包作为开发依赖安装到项目中。在执行此操作前,请确保项目中存在 package.json 文件。 ```bash npm install --save-dev eslint ``` -------------------------------- ### Error Example: Modifying Read-Only Globals (JavaScript) Source: https://zh-hans.eslint.org/docs/latest/rules/no-native-reassign This example shows incorrect usage of the `no-native-reassign` rule, where assignments are made to `Object`, `undefined`, and browser-specific globals like `window`, `length`, and `top`. The rule flags these as errors because these are typically native or read-only. ```javascript /*eslint no-native-reassign: "error"*/ Object = null undefined = 1 ``` ```javascript /*eslint no-native-reassign: "error"*/ /*eslint-env browser*/ window = {} length = 1 top = 1 ``` ```javascript /*eslint no-native-reassign: "error"*/ /*eslint-global a:readonly*/ a = 1 ``` -------------------------------- ### JSON 扩展插件和推荐规则 Source: https://zh-hans.eslint.org/docs/latest/use/configure/configuration-files 使用 JSON 格式配置 ESLint,同时扩展 `eslint:recommended` 和一个插件(如 `react/recommended`),并自定义插件规则。适用于 React 项目或其他需要集成特定插件的项目。 ```json { "plugins": [ "react" ], "extends": [ "eslint:recommended", "plugin:react/recommended" ], "rules": { "react/no-set-state": "off" } } ``` -------------------------------- ### ESLint 'semi': 'never' - Error Example Source: https://zh-hans.eslint.org/docs/latest/rules/semi Illustrates code that violates the 'semi' rule when configured to 'never' require semicolons. This typically occurs when semicolons are present at the end of statements where they are not permitted. ```javascript /*eslint semi: ["error", "never"]*/ var name = "ESLint"; object.method = function() { // ... }; class Foo { bar = 1; } 1 2 3 4 5 6 7 8 9 10 11 ``` -------------------------------- ### 安装 ESLint 依赖项 Source: https://zh-hans.eslint.org/docs/latest/contribute/development-environment 在克隆仓库后,安装项目所需的所有 npm 依赖项。此步骤需要网络连接。 ```bash cd eslint npm install ``` -------------------------------- ### ESLint 'semi': 'always' - Correct Example Source: https://zh-hans.eslint.org/docs/latest/rules/semi Shows correctly formatted JavaScript code that adheres to the 'semi' rule when configured to 'always' require semicolons. All statements correctly end with a semicolon. ```javascript /*eslint semi: "error"*/ var name = "ESLint"; object.method = function() { // ... }; class Foo { bar = 1; } 1 2 3 4 5 6 7 8 9 10 11 ``` -------------------------------- ### 运行 ESLint CLI Source: https://zh-hans.eslint.org/docs/latest/use/command-line-interface 使用 npx 在命令行中运行 ESLint,可以指定要检查的文件、目录或 glob 模式。这是执行代码检查的标准方式。注意 glob 模式可能需要引号以确保正确解析。 ```bash npx eslint [options] [file|dir|glob]* # 检查两个文件 npx eslint file1.js file2.js # 检查多个文件 npx eslint lib/** # 使用 node 的 glob 语法(需加引号) npx eslint "lib/**" ``` -------------------------------- ### Object Literal Spacing Examples (JavaScript) Source: https://zh-hans.eslint.org/docs/latest/rules/object-curly-spacing Demonstrates basic object literal structures with and without spacing, including nested objects and destructuring assignments. This serves as an introduction to the concept of object-curly-spacing. ```javascript var obj = { foo: "bar" }; var obj = { foo: { zoo: "bar" } }; var { x, y } = y; import { foo } from "bar"; export { foo }; ``` -------------------------------- ### Error Example: Redeclaring Browser Globals (JavaScript) Source: https://zh-hans.eslint.org/docs/latest/rules/no-redeclare Demonstrates an error when 'no-redeclare' with 'builtinGlobals: true' is used in a browser environment, showing the redeclaration of a browser-specific global variable like 'top'. ```javascript /*eslint no-redeclare: ["error", { "builtinGlobals": true }]*/ /*eslint-env browser*/ var top = 0; ``` -------------------------------- ### Ignoring Property Modifications with Regex (JavaScript) Source: https://zh-hans.eslint.org/docs/latest/rules/no-param-reassign This example demonstrates using `ignorePropertyModificationsForRegex` with `props: true`. It allows modifications to properties of parameters whose names match the provided regular expression (e.g., starting with 'bar'). ```javascript /*eslint no-param-reassign: ["error", { "props": true, "ignorePropertyModificationsForRegex": ["^bar"] }]*/ var foo = function(barVar) { barVar.prop = "value"; } var foo = function(barrito) { delete barrito.aaa; } var foo = function(bar_) { bar_.aaa++; } var foo = function(barBaz) { for (barBaz.aaa in baz) {} } var foo = function(barBaz) { for (barBaz.aaa of baz) {} } ``` -------------------------------- ### 设置 ESLint 插件解析目录 (--resolve-plugins-relative-to) Source: https://zh-hans.eslint.org/docs/latest/use/command-line-interface 修改 ESLint 解析插件的文件夹位置。当配置文件或插件位于非标准位置时使用。应设置为包含配置文件的目录。 ```bash npx eslint --config ~/personal-eslintrc.js \ --resolve-plugins-relative-to /usr/local/lib/ ``` -------------------------------- ### ESLint CLI 指定配置文件 Source: https://zh-hans.eslint.org/docs/latest/use/command-line-interface 使用 `-c` 或 `--config` 选项可以指定一个自定义的 ESLint 配置文件,该配置将覆盖 `.eslintrc.*` 和 `package.json` 中的任何现有配置。此选项接受一个文件路径作为参数。 ```bash npx eslint -c ~/my-eslint.json file.js ``` -------------------------------- ### 指定 ESLint 自定义规则目录 (--rulesdir) Source: https://zh-hans.eslint.org/docs/latest/use/command-line-interface 指定一个目录,ESLint 将从该目录加载自定义规则文件。规则需要显式启用。此选项已废弃,推荐使用插件。 ```bash npx eslint --rulesdir my-rules/ file.js npx eslint --rulesdir my-rules/ --rulesdir my-other-rules/ file.js ``` -------------------------------- ### Yoda Conditions: Allow Yoda Style (always) - Correct Examples Source: https://zh-hans.eslint.org/docs/latest/rules/yoda Demonstrates correct usage when the 'always' option is enabled, showing instances where literal values correctly precede variables in comparisons. ```javascript /*eslint yoda: ["error", "always"]*/ if ("blue" == value) { // ... } if (`blue` == value) { // ... } if (`blue` == `${value}`) { // ... } if (-1 < str.indexOf(substr)) { // ... } ``` -------------------------------- ### ESLint 'semi': 'always', omitLastInOneLineBlock - Correct Example Source: https://zh-hans.eslint.org/docs/latest/rules/semi Shows correct code adhering to the 'semi' rule with 'always' and 'omitLastInOneLineBlock: true'. This option allows omitting the last semicolon in a one-line block. ```javascript /*eslint semi: ["error", "always", { "omitLastInOneLineBlock": true}] */ if (foo) { bar() } if (foo) { bar(); baz() } function f() { bar(); baz() } class C { foo() { bar(); baz() } static { bar(); baz() } } 1 2 3 4 5 6 7 8 9 10 11 12 13 ``` -------------------------------- ### Create ESLint Instance with Custom Configuration (Node.js) Source: https://zh-hans.eslint.org/docs/latest/integrate/integration-tutorial Imports the ESLint class from the 'eslint' package and creates a new instance. The ESLint instance can be customized by passing an options object to the constructor, allowing for overrides of the ESLint configuration and enabling automatic fixing. ```javascript // example-eslint-integration.js const { ESLint } = require("eslint"); // Create an instance of ESLint with the configuration passed to the function function createESLintInstance(overrideConfig){ return new ESLint({ useEslintrc: false, overrideConfig: overrideConfig, fix: true }); } ``` -------------------------------- ### ESLint 'semi': 'always' - Error Example Source: https://zh-hans.eslint.org/docs/latest/rules/semi Demonstrates incorrect code when the 'semi' rule is configured to 'always' require semicolons at the end of statements. This typically involves missing semicolons where the rule expects them. ```javascript /*eslint semi: ["error", "always"]*/ var name = "ESLint" object.method = function() { // ... } class Foo { bar = 1 } 1 2 3 4 5 6 7 8 9 10 11 ``` -------------------------------- ### ESLint Output for Visual Studio Integration Source: https://zh-hans.eslint.org/docs/latest/use/formatters This example demonstrates the typical output format of ESLint when configured for Visual Studio IDE integration. This format allows the IDE to parse the errors and warnings, providing clickable links to the exact location in the source code where the issue is found. No specific dependencies are required beyond ESLint itself, and the input is the code being linted. ```text /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(1,10): error no-unused-vars : 'addOne' is defined but never used. /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(2,9): error use-isnan : Use the isNaN function to compare with NaN. /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(3,16): error space-unary-ops : Unexpected space before unary operator '++'. /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(3,20): warning semi : Missing semicolon. /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(4,12): warning no-else-return : Unnecessary 'else' after 'return'. /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(5,1): warning indent : Expected indentation of 8 spaces but found 6. /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(5,7): error consistent-return : Function 'addOne' expected a return value. /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(5,13): warning semi : Missing semicolon. /var/lib/jenkins/workspace/Releases/eslint Release/eslint/fullOfProblems.js(7,2): error no-extra-semi : Unnecessary semicolon. 9 problems ``` -------------------------------- ### 克隆 ESLint 仓库 Source: https://zh-hans.eslint.org/docs/latest/contribute/development-environment 克隆 ESLint 的 Git 仓库到本地。请将 `<你的 Github 用户名>` 替换为你的实际 GitHub 用户名。 ```bash git clone https://github.com/<你的 Github 用户名>/eslint ``` -------------------------------- ### Shorter Code with void 0 - JavaScript Source: https://zh-hans.eslint.org/docs/latest/rules/no-void This example illustrates a common use case for the `void` operator: shortening code by using `void 0` instead of `undefined`, as `void 0` is more concise. ```javascript foo = void 0; foo = undefined; ``` -------------------------------- ### ESLint 命令行配置示例 Source: https://zh-hans.eslint.org/docs/latest/use/configure/configuration-files-new 使用 `--config` 选项指定 ESLint 配置文件,并指定要检查的文件。这允许您在不使用默认配置文件的情况下应用自定义配置。 ```bash eslint -c myconfig.json myfiletotest.js ``` -------------------------------- ### Get ESLint Static Version Source: https://zh-hans.eslint.org/docs/latest/integrate/nodejs-api Demonstrates how to access the ESLint version directly from the `Linter` class without instantiating it, using the static `Linter.version` property. This is useful for quickly checking the installed ESLint version. ```javascript const Linter = require("eslint").Linter; Linter.version; // => '4.5.0' ``` -------------------------------- ### 配置 ESLint 解析器选项 (--parser-options) Source: https://zh-hans.eslint.org/docs/latest/use/command-line-interface 为 ESLint 指定的解析器提供选项。选项的可用性取决于所选的解析器。支持由分号分割的键值对。 ```bash echo '3 ** 4' | npx eslint --stdin --parser-options ecmaVersion:6 # 解析错误,失败 echo '3 ** 4' | npx eslint --stdin --parser-options ecmaVersion:7 # 耶!成功 ``` -------------------------------- ### Configure ESLint destructuredArrayIgnorePattern in JavaScript Source: https://zh-hans.eslint.org/docs/latest/rules/no-unused-vars The 'destructuredArrayIgnorePattern' option allows ESLint to ignore elements in destructured array assignments whose names match a given regular expression. This example ignores array elements starting with an underscore. ```javascript /*eslint no-unused-vars: ["error", { "destructuredArrayIgnorePattern": "^_” }]*/ const [a, _b, c] = ["a", "b", "c"]; console.log(a+c); const { x: [_a, foo] } = bar; console.log(foo); function baz([_c, x]) { x; } baz(); function test({p: [_q, r]}) { r; } test(); let _m, n; foo.forEach(item => { [_m, n] = item; console.log(n); }); let _o, p; _o = 1; [_o, p] = foo; p; ``` -------------------------------- ### Correct usage of lines-around-comment with allowClassStart (beforeLineComment) Source: https://zh-hans.eslint.org/docs/latest/rules/lines-around-comment This example demonstrates the correct implementation of the 'lines-around-comment' rule with 'beforeLineComment' set to true and 'allowClassStart' to false. It shows that a blank line is required before a line comment if it appears within the class body but not at the very start. ```javascript /*eslint lines-around-comment: ["error", { "beforeLineComment": true, "allowClassStart": false }]*/ class foo { // what a great and wonderful day day() {} }; ``` -------------------------------- ### 集成 ESLint 代码检查和修复 (JavaScript) Source: https://zh-hans.eslint.org/docs/latest/integrate/integration-tutorial 此代码段演示了如何使用 ESLint API 集成代码检查和修复功能。它定义了一个 `lintFiles` 函数,该函数接受文件路径数组,配置 ESLint 实例,执行 linting 和修复,然后输出结果。该函数还包括用于创建 ESLint 实例、执行 linting 和修复以及输出结果的辅助函数。 ```javascript const { ESLint } = require("eslint"); // Create an instance of ESLint with the configuration passed to the function function createESLintInstance(overrideConfig){ return new ESLint({ useEslintrc: false, overrideConfig: overrideConfig, fix: true }); } // Lint the specified files and return the results async function lintAndFix(eslint, filePaths) { const results = await eslint.lintFiles(filePaths); // Apply automatic fixes and output fixed code await ESLint.outputFixes(results); return results; } // Log results to console if there are any problems function outputLintingResults(results) { // Identify the number of problems found const problems = results.reduce((acc, result) => acc + result.errorCount + result.warningCount, 0); if (problems > 0) { console.log("Linting errors found!"); console.log(results); } else { console.log("No linting errors found."); } return results; } // Put previous functions all together async function lintFiles(filePaths) { // The ESLint configuration. Alternatively, you could load the configuration // from a .eslintrc file or just use the default config. const overrideConfig = { env: { es6: true, node: true, }, parserOptions: { ecmaVersion: 2018, }, rules: { "no-console": "error", "no-unused-vars": "warn", }, }; const eslint = createESLintInstance(overrideConfig); const results = await lintAndFix(eslint, filePaths); return outputLintingResults(results); } // Export integration module.exports = { lintFiles } ``` -------------------------------- ### ESLint 'semi': 'never' - Correct Example Source: https://zh-hans.eslint.org/docs/latest/rules/semi Presents correctly formatted JavaScript code that follows the 'semi' rule when configured to 'never' require semicolons. Semicolons are omitted at the end of statements, relying on ASI. ```javascript /*eslint semi: ["error", "never"]*/ var name = "ESLint" object.method = function() { // ... } var name = "ESLint" ;(function() { // ... })() import a from "a" (function() { // ... })() import b from "b" ;(function() { // ... })() class Foo { bar = 1 } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 ``` -------------------------------- ### ESLint: 仅报告错误 (`--quiet`) Source: https://zh-hans.eslint.org/docs/latest/use/command-line-interface 启用 `--quiet` 选项后,ESLint 将只会报告错误,而忽略所有警告。这有助于在 CI/CD 环境中只关注严重的问题。 ```bash npx eslint --quiet file.js ``` -------------------------------- ### ESLint Flat Configuration with Multiple Overrides (.eslint.config.js) Source: https://zh-hans.eslint.org/docs/latest/use/configure/migration-guide This example demonstrates the ESLint flat configuration with multiple overrides targeting different file patterns. It shows how to combine a base recommended configuration with specific rule adjustments for 'src' and 'test' files, providing flexibility in linting. ```javascript // eslint.config.js import js from "@eslint/js"; export default [ js.configs.recommended, // Recommended config applied to all files // File-pattern specific overrides { files: ["src/**/*", "test/**/*"], rules: { semi: ["warn", "always"] } }, { files:["test/**/*"], rules: { "no-console": "off" } } // ...other configurations ]; ``` -------------------------------- ### Error Example: Redeclaring 'var' Variables (JavaScript) Source: https://zh-hans.eslint.org/docs/latest/rules/no-redeclare This code snippet demonstrates incorrect usage of the 'no-redeclare' rule by redeclaring variables declared with 'var' in the same scope. This is flagged as an error by ESLint when the rule is enabled. ```javascript /*eslint no-redeclare: "error"*/ var a = 3; var a = 10; class C { foo() { var b = 3; var b = 10; } static { var c = 3; var c = 10; } } ``` -------------------------------- ### YAML 配置文件设置根目录 Source: https://zh-hans.eslint.org/docs/latest/use/configure/configuration-files-new 在 YAML 格式的 ESLint 配置文件中设置 `root: true`,以防止 ESLint 在当前目录之上的父文件夹中继续搜索配置文件。这限制了配置的级联范围。 ```yaml --- root: true ``` -------------------------------- ### Configure ESLint caughtErrorsIgnorePattern in JavaScript Source: https://zh-hans.eslint.org/docs/latest/rules/no-unused-vars The 'caughtErrorsIgnorePattern' option allows specifying a regular expression to ignore unused caught error parameters whose names match the pattern. This example shows how to ignore catch parameters starting with 'ignore'. ```javascript /*eslint no-unused-vars: ["error", { "caughtErrorsIgnorePattern": "^ignore" }]*/ try { //... } catch (ignoreErr) { console.error("errors"); } ``` -------------------------------- ### ESLint: 启用缓存 (`--cache`) Source: https://zh-hans.eslint.org/docs/latest/use/command-line-interface 启用 `--cache` 选项后,ESLint 会缓存检查结果,只对发生更改的文件进行重新检查。这能显著提高 ESLint 的运行速度,尤其是在大型项目中。 ```bash npx eslint --cache file.js ``` -------------------------------- ### JavaScript: Correct constructor naming with ESLint rule Source: https://zh-hans.eslint.org/docs/latest/rules/new-cap Shows the correct usage of constructor functions with ESLint's `new-cap` rule enabled. This example adheres to the rule by starting the constructor name `Boolean` with an uppercase letter. ```javascript /*eslint new-cap: "error"*/ function foo(arg) { return Boolean(arg); } ``` -------------------------------- ### ESLint CLI 禁用eslintrc配置 Source: https://zh-hans.eslint.org/docs/latest/use/command-line-interface 使用 `--no-eslintrc` 选项可以禁用 ESLint 对 `.eslintrc.*` 和 `package.json` 文件中的配置的查找。这在需要完全控制配置时很有用。此选项仅适用于 eslintrc 模式。 ```bash npx eslint --no-eslintrc file.js ``` -------------------------------- ### Disallow Specific Modules with Custom Messages (JavaScript) Source: https://zh-hans.eslint.org/docs/latest/rules/no-restricted-imports This example illustrates how to restrict imports of specific modules like 'cluster' and provides custom error messages to guide developers. It showcases the ESLint configuration for targeted module restrictions. ```javascript /*eslint no-restricted-imports: ["error", { "paths": ["cluster"] }]*/ import cluster from 'cluster'; 1 2 3 ``` -------------------------------- ### Correct Example: Assigning to 'var' Variables (JavaScript) Source: https://zh-hans.eslint.org/docs/latest/rules/no-redeclare This code snippet shows the correct usage where variables are assigned new values instead of being redeclared. ESLint's 'no-redeclare' rule allows re-assignment but flags redeclaration. ```javascript /*eslint no-redeclare: "error"*/ var a = 3; a = 10; class C { foo() { var b = 3; b = 10; } static { var c = 3; c = 10; } } ``` -------------------------------- ### ESLint: 指定输出格式 (`-f`, `--format`) Source: https://zh-hans.eslint.org/docs/latest/use/command-line-interface 使用 `-f` 或 `--format` 选项可以指定 ESLint 的输出格式。支持内置格式(如 'compact')和自定义格式(本地文件或 npm 包)。 ```bash npx eslint -f compact file.js npx eslint -f ./customformat.js file.js npm install eslint-formatter-pretty npx eslint -f pretty file.js ``` -------------------------------- ### ESLint 'argsIgnorePattern' to Ignore Specific Parameters Source: https://zh-hans.eslint.org/docs/latest/rules/no-unused-vars The `argsIgnorePattern` option allows you to specify a regular expression for ignoring function parameters based on their names. In this example, parameters starting with an underscore (`_`) are ignored by the `no-unused-vars` rule, useful for indicating intentionally unused parameters. ```javascript /*eslint no-unused-vars: ["error", { "argsIgnorePattern": "^_” }]*/ function foo(x, _y) { return x + 1; } foo(); 1 2 3 4 5 6 ``` -------------------------------- ### 安装 ESLint FlatCompat 包 Source: https://zh-hans.eslint.org/docs/latest/use/configure/migration-guide 当需要将旧的 eslintrc 格式配置迁移到平面配置文件格式时,需要安装 `@eslint/eslintrc` 包。 ```bash npm install @eslint/eslintrc --save-dev ``` -------------------------------- ### ESLint spaced-line-comment Rule: 'always' Option Source: https://zh-hans.eslint.org/docs/latest/rules/spaced-line-comment This example shows the 'always' option for the spaced-line-comment rule, enforcing at least one space after the '//' in line comments. This improves readability of the comment text. The default behavior is 'always'. ```javascript //When ["always"] //This is a comment with no whitespace at the beginning var foo = 5; 1 2 3 ``` -------------------------------- ### ESLint Basic Rule Configuration (.eslintrc.js) Source: https://zh-hans.eslint.org/docs/latest/use/configure/migration-guide This example shows a basic .eslintrc.js configuration file that sets a specific rule (semi-colon warning) for all files in the directory and its subdirectories. It is a common pattern for defining project-wide linting rules. ```javascript // .eslintrc.js module.exports = { // ...other config rules: { semi: ["warn", "always"] } }; ``` -------------------------------- ### ESLint 'semi': 'never', beforeStatementContinuationChars: 'always' - Error Example Source: https://zh-hans.eslint.org/docs/latest/rules/semi Demonstrates an error case for the 'semi' rule when configured to 'never' with 'beforeStatementContinuationChars: "always"'. This occurs when a statement continuation character is present, and a semicolon is expected but missing. ```javascript /*eslint semi: ["error", "never", { "beforeStatementContinuationChars": "always"}] */ import a from "a" (function() { // ... })() 1 2 3 4 5 6 ``` -------------------------------- ### 指定 ESLint 文件扩展名 (--ext) Source: https://zh-hans.eslint.org/docs/latest/use/command-line-interface 指定 ESLint 在目录中匹配文件时使用的文件扩展名。支持单个或多个扩展名,支持逗号分隔的列表。 ```bash # 仅 .ts 扩展 npx eslint . --ext .ts # 同时使用 .js 和 .ts npx eslint . --ext .js --ext .ts # 也是同时使用 .js 和 .ts npx eslint . --ext .js,.ts ``` -------------------------------- ### Object Curly Spacing: 'never' Option Examples (JavaScript) Source: https://zh-hans.eslint.org/docs/latest/rules/object-curly-spacing Illustrates correct and incorrect usage of object curly spacing when the 'never' option is applied. This option disallows spacing inside braces, except for the empty object literal. ```javascript /*eslint object-curly-spacing: ["error", "never"]*/ // Incorrect examples var obj = { 'foo': 'bar' }; var obj = {'foo': 'bar' }; var obj = { baz: {'foo': 'qux'}, bar}; var obj = {baz: { 'foo': 'qux'}, bar}; var {x } = y; import { foo } from 'bar'; // Correct examples var obj = {'foo': 'bar'}; var obj = {'foo': {'bar': 'baz'}, 'qux': 'quxx'}; var obj = { 'foo': 'bar' }; var obj = {'foo': 'bar' }; var obj = { 'foo':'bar'}; var obj = {}; var {x} = y; import {foo} from 'bar'; ```