首页 > web前端 > js教程 > 正文

ESLint 采用指南:概述、示例和替代方案

WBOY
发布: 2024-08-08 22:30:52
原创
443 人浏览过

由塞巴斯蒂安·韦伯撰写✏️

多年来,ESLint 一直是 JavaScript 和 TypeScript 项目 linting 的事实上的标准。本采用指南解释了为什么 2024 年仍然如此。

本文介绍了 ESLint 的当前版本,该版本于 2024 年夏季发布(v9.7)。因此,仅描述 v9 的概念和特性,与之前的版本相比,它带来了一些重大的突破性变化。

如果您想使用旧版本而不使用带有平面配置文件的最新配置风格,您可以查阅官方迁移指南。

什么是 ESLint?

ESLint 是一个可配置且可扩展的 JavaScript linter,用于执行静态代码分析。它可以帮助您跟踪和解决源代码中的问题,而无需执行它。问题可以是任何事情,从潜在的运行时错误、不良的编码实践到代码格式问题。

作为软件质量工具,ESLint 旨在使代码更加一致和健壮。它借助断言(即所谓的 lint 规则)检查代码,了解代码的外观或行为。例如,使用 no-use-before-define 规则,您可以指示 ESLint 在声明之前遇到函数调用时报告违规行为。

此外,可以将每条规则的违规严重程度指定为警告或错误。因此,在 CI/CD 管道中,检测步骤可能会因报告的错误而失败,这表明需要调查更大的问题。

在解析器和插件的帮助下,ESLint 可以配置为理解和检查 TypeScript 或 JavaScript 语法扩展(如 JSX),或 JavaScript 框架(如 React 或 Vue)的概念。

为什么创建 ESLint?

ESLint 的想法是由于当时可用的 linting 工具(例如 JSCS、JSLint 和 JSHint)的不足而产生的。这些工具的规则集和配置功能有些僵化,很难根据具体的项目需求调整规则。

自从 ESLint 的初始版本以来,规则就构建了 ESLint 的主干。他们可能会提供有关如何手动解决直接显示在代码编辑器内有问题的代码位置(带有标记和覆盖)的违规问题的建议。

此外,规则可能会提供修复,使 ESLint 能够自动解决 CLI 或代码编辑器中的违规问题;例如,将箭头函数重构为隐式返回变体。

除了通过更广泛的工具和语言支持提供更好的 linting 体验之外,ESLint 的另一个卖点过去是,现在仍然是可插拔架构。与竞争对手相比,它具有更大的可扩展性和可定制性,允许开发人员创建和共享自定义规则并将 ESLint 扩展到其核心功能之外。

ESLint 多年来崛起的证据是它与 JSCS 合并,而 JSCS 随着时间的推移正在节节败退。自诞生以来,ESLint 已经发生了显着的发展:

  • ES6 及更高版本 — ESLint 不断更新其规则集以适应新的 ECMAScript 标准,提供对最新 JavaScript 功能和语法扩展的原生支持,例如 JSX。您还可以借助相关项目扩展 ESLint 以理解其他语言;例如,typescript-eslint 支持 TypeScript
  • 集成和生态系统 — 该工具与各种开发环境、构建工具(例如用于 Prettier 格式的 ESLint 插件)和代码编辑器(例如 ESLint VS Code 扩展)有了更好的集成。社区为不同的库和框架贡献了广泛的插件(例如,Vue.js 的官方 ESLint 插件)来支持 Vue 的单文件组件,使 ESLint 在不同的 JavaScript 生态系统中具有通用性
  • 性能改进 - 随着时间的推移,ESLint 取得了显着的性能改进,使得分析大型代码库变得更快。

在维护 JavaScript 项目中的代码质量和一致性方面,ESLint 是一个出色的工具。将其采用到您的项目中可以显着增强 DX,确保您的代码库保持干净、可读且没有错误。

ESLint 附带了许多规则,可以轻松地根据项目的要求进行调整。您甚至可以借助社区插件添加更多规则。此外,解析器可用于扩展 ESLint 的功能。

进一步阅读:

  • 使用 Prettier 和 ESLint 进行 JavaScript 格式化

使用 ESLint

在深入研究 ESLint 的核心概念和功能之前,我们需要先设置 ESLint 工作流程。

将 ESLint 添加到您的项目中

在已有 package.json 的文件夹中,您可以运行以下命令将 ESLint 添加到您的开发项目中。 ESLint 旨在本地安装。使用以下命令,您可以运行交互式安装指南,添加默认的 ESLint 配置:

# run at root level of your project
$ npm init @eslint/config@latest
登录后复制

您还可以使用可共享的配置来初始化您的项目。您可以通过执行 Github 搜索找到其中的许多内容。命名约定是以 eslint-config- 开始自定义配置。

安装向导会询问您几个有关当前项目设置的问题:ESLint adoption guide: Overview, examples, and alternatives完成安装后,ESLint 创建了一个配置文件,其文件后缀取决于您选择的模块变体的类型。对于 ESM,您可以在工作目录中找到 eslint.config.mjs。作为惯例,.mjs 文件前缀表示您的项目使用 ESM,但 eslint.config.js 具有相同的效果。

使用 ESLint 的平面配置

这个所谓的普通 JavaScript 项目的平面配置最初看起来像这样:

// eslint.config.mjs
import globals from "globals";
import pluginJs from "@eslint/js";
export default [
  { languageOptions: { globals: globals.browser } },
  pluginJs.configs.recommended,
];
登录后复制

通过上面的配置,默认的 ESLint JavaScript npm 包 @eslint/js 与浏览器环境 (globals.browser) 和所有推荐的 JS 规则一起使用。让我们创建一个简单的 JavaScript 文件,其中包含一些违反规则的内容:

// playground.js
var testVar = "This should be 'let' or 'const'";
undefinedFunctionCall();
登录后复制

我们利用 ESLint CLI 和 npx,其路径与 eslint.config.mjs 所在的路径相同:

$ npx eslint # all files recursively
$ npx eslint playground.js # specific file(s)
$ npx eslint *.js # ESLint supports globs
登录后复制

在此示例中,ESLint 由于违反 no-unused-vars 和 no-undef 规则而报告了两个错误: ESLint adoption guide: Overview, examples, and alternatives ESLint GitHub 项目是在 monorepo 中组织的,您可以通过查看来查阅更多配置选项@eslint/js 包。上面的配置添加了所有推荐的规则,这些规则都有错误的严重级别。我们稍后将了解有关违规严重程度的更多信息。

以下配置演示了使用推荐规则的不同变体:

export default [
  // ...
  // pull in all recommended rules
  pluginJs.configs.recommended,
  // all but different approach
  { rules: pluginJs.configs.recommended.rules },
  // all but override existing rules
  {
    rules: {
      ...pluginJs.configs.recommended.rules,
      // change the severity level
      "no-unused-vars": "warn",
    },
  }
];
登录后复制

以下代码片段演示了 ESLint 提供了开箱即用的 JavaScript 规则,因为您可以通过知道名称来使用它们,而无需导入任何内容。但是,不建议这样做:

import globals from "globals";
export default [
  { languageOptions: { globals: globals.browser } },
  {
    rules: {
      "no-unused-vars": "warn",
    },
  },
];
登录后复制

将 ESLint 与您的代码编辑器集成

有多种方法可以将 ESLint 集成到工具链、编辑器和 IDE 中。如果您希望 VS Code 突出显示源文件中的规则违规,您只需安装官方 ESLint 扩展: ESLint adoption guide: Overview, examples, and alternatives 如果您发现 VS Code 中的 ESLint 扩展不响应您的配置更改,以下选项之一通常会对您有所帮助。

首先,查看 VS Code 的输出面板,从下拉列表中选择 ESLint,然后查找错误: ESLint adoption guide: Overview, examples, and alternatives 其次,在命令面板的帮助下重新启动内部 ESLint 服务器并执行 ESLint:Restart ESLint Server .

添加 TypeScript 支持

通过交互式安装指南,如果您选择 TypeScript,配置将利用 typescript-eslint 来教 ESLint 如何解释 TypeScript。您还可以手动安装 TypeScript 支持。确保安装与 ESLint v9 和平面配置兼容的正确版本(≥ v8.0.0-alpha.10):

$ npm i -D eslint @eslint/js @types/eslint__js typescript typescript-eslint@8.0.0-alpha.10 --force
登录后复制

通过以下配置,您可以结合使用 ESLint 推荐的 JavaScript 规则和 typescript-eslint 提供的推荐 TypeScript 规则:

// eslint.config.mjs
import eslint from "@eslint/js";
import tseslint from "typescript-eslint";
export default tseslint.config(
  eslint.configs.recommended,
  ...tseslint.configs.recommended
);
登录后复制

下一个屏幕截图显示 npx eslint 以及 VS Code ESLint 扩展均报告 JS 和 TS 违规:ESLint adoption guide: Overview, examples, and alternatives

需要了解的关键 ESLint 概念和功能

上一节深入了解了 ESLint 的设置和使用方式。接下来,我将介绍您需要了解的核心概念,以便使用 ESLint 获利。

有关平面配置的更多信息

采用新的平面配置概念,整个项目配置是一个 eslint.config.js(c|j|m) 文件的一部分。以前,配置可能分布在多个 .eslintrc 文件中,甚至是 package.json 的一部分,这导致了复杂性和混乱。

Typically your flat config file is slim, as ESLint comes with reasonable default values for projects. By default, ESLint searches for source files with the suffixes .js, .mjs, and .cjs. In what follows, the terms flat config and eslint.config are used synonymously. The latter is representative of all file extensions (.*js).

When you use typescript-eslint, out-of-the-box ESLint will lint .ts, .tsx, .mts, and .cts files. As another example, all files with prefix .cjs are treated as JS files using CommonJS modules. Further, ecmaVersion: "latest" is the default, so ESLint expects you to work with the most recent version of ECMAScript:

{
  files: ["**/*.cjs"],
  languageOptions: {
      sourceType: 'commonjs',
      ecmaVersion: 'latest'
  },
},
登录后复制

How do you know about these default values? ESLint ships a handy visual tool to inspect your eslint.config. With the ESLint Config Inspector, you learn how the configuration concept works. Similar to the CSS DevTools in browsers, where you can see how the styles come about, you find out what default values are applied or how rules get applied for different file globs: ESLint adoption guide: Overview, examples, and alternatives This tool is valuable since the effective configuration object returned by eslint.config may not be apparent when simply looking at the file. This is especially true because you can import external configurations or generate parts of the configuration on the fly. You can run it with the following command:

$ npx @eslint/config-inspector
登录后复制

The concept of eslint.config is pretty straightforward, you have to return an array of config objects. Every config object adds either configuration for all files or a subset of files specified by a file glob. Consequently, multiple config objects can be composed to an overall configuration. If you skip the files property, the config object applies to all files: ESLint adoption guide: Overview, examples, and alternatives ESLint takes care to merge all the config objects into one effective configuration. This can be traced with the help of the ESLint Config Inspector.

For files matching *.jsx, the languageOption is configured to interpret JSX files. Otherwise, ESLint does not understand how to handle JSX files. The optional name property is useful in combination with the Config Inspector to improve traceability: ESLint adoption guide: Overview, examples, and alternatives The languageOptions property is where ESLint gets to know what module system, ECMAScript version, or language extension you want to use. In the previous example, we told ESLint how to interpret JSX files with languageOptions.parserOptions.ecmaFeatures.jsx property.

You can opt out of the latest ECMAScript version — e.g., ecmaVersion: 2015. ESLint also assumes that ESM is the way you handle JS modules in your project. Therefore, the default is sourceType: "module" for .js and .jsm files. Otherwise, you have to opt out (sourceType: "script"). For .cjs files, the default is sourceType: "commonjs".

Another useful property is languageOptions.globals. In projects for the browser environment, ESLint needs to know global variables like window or console. Otherwise, ESLint incorrectly reports a no-undef error: ESLint adoption guide: Overview, examples, and alternatives You can specify your project-specific global variables with languageOptions.globals. For browser projects, you can import globals, which is a JSON file holding predefined global identifiers:

import globals from "globals";
// ...
export default [
  {
    name: "globals",
    languageOptions: {
      globals: globals.browser,
    },
  },
  // ...
];
登录后复制

Again, you can utilize the Config Inspector to see all global variable names: ESLint adoption guide: Overview, examples, and alternatives You can read about all configuration capabilities in the official docs.

How to work with rules

For many projects, starting with a predefined rule set as provided by @eslint/js is a good choice. These sets provide a broad coverage of common issues and, if required, stylistic preferences.

When you run ESLint, either via CLI or the background process inside your code editor, rule violations are reported. For every violation, ESLint shows the rule ID (e.g., no-undef) and a short violation explanation.

With that rule ID, you can easily navigate to the rule detail page from the rules reference. Alternatively, from the VS Code extension (or any other code editor integration), you can click on the provided link: ESLint adoption guide: Overview, examples, and alternatives Every rule has an easy-to-read documentation page following the same structure, including a helpful TOC on the right: ESLint adoption guide: Overview, examples, and alternatives The rule details are handy for multiple reasons:

  • Find out what the rule is all about
  • Read about correct and incorrect code examples
  • Examine all rule-specific options

The latter is relevant to finding out how to tweak the rule inside of eslint.config.

There’s an important concept called violation severities. Every rule has a default severity level. You can change the severity level for every rule in eslint.config. There are three levels of severity:

  • off or 0 — Turn a rule off; i.e., ESLint will not check for this particular rule
  • warn or 1 — A warning indicates a potential issue that, while not necessarily violating best practices or causing errors, might lead to confusion or less readable code. Warnings are meant to draw attention to something that might need review but most likely don't break anything. Warnings don't affect exit codes, meaning your CLI command will not be canceled
  • error or 2 — An error indicates a significant issue that likely violates best practices or could lead to bugs. Errors are considered serious and should be addressed promptly. The CLI process does not terminate but exits with status code 1

To change a rule’s severity, set the rule ID equal to one of these values. The following example config demonstrates how to tweak different rules:

// eslint.config.js
import pluginJs from "@eslint/js";
// override default values
const modifiedRules = {
  // create a copy of the recommended rules to modify
 ...pluginJs.configs.recommended.rules,
 // turn rule off
 'no-unused-vars': 0,
 // Require the use of === and !== 
 // change default from error to warning
 'eqeqeq': 1,
 // Disallow the use of variables before they are defined.
 // Except for hoisted functions
 'no-use-before-define': ["error", { "functions": false }]
}
export default [
  {
    name: "ESLint recommended rules with modifications",
    rules: modifiedRules,
  },
];
登录后复制

The last example, no-use-before-define, demonstrates how to look up the options in the documentation and change them according to your preferences.

Most lint rules fall into one of two to three categories:

  • Logical rules focus on the correctness and expected behavior of code during execution. Examples include ensuring promises are properly awaited
  • Stylistic rules focus on the coding style you use that does not impact the runtime behavior, such as favoring one syntax variant over the other (e.g., function declarations vs. arrow functions)
  • Formatting rules constitute a subset of stylistic rules that are solely concerned with code beautifying (e.g., use semicolons or not)

The use of stylistic rules falls into the scope of tools such as Prettier, which solely deal with code formatting. ESLint's stylistic rules (e.g., indent) may conflict with such dedicated formatters.

In October 2023, the ESLint team decided to deprecate all formatting rules, mainly for maintainability and architectural reasons. They have reserved the right to remove it from v10 onwards. You still have different options for combining ESLint with code formatting, as I will explain in the next section.

Later, we’ll discuss several options to use ESLint for code formatting.

Configuration comments

You've already seen one variant to configure rules inside of eslint.config. Alternatively, to configure rules inside of a file, you can leverage configuration comments:

/* eslint no-unused-vars: "off" */
let unusedVariable;
/* eslint eqeqeq: "warn" */
"hello world!" == "hello world"
/* eslint no-use-before-define: ["error", { "functions": false }] */
let x = usedBeforeDefined();
function usedBeforeDefined() {
  return true;
}
登录后复制

It's also possible to turn off rules with inline comments. This should only be used temporarily during development. Further, you should only commit these comments to VCS in exceptional cases. You can disable a rule for the whole file or the next line:

// the following disables the rule for the whole file
/* eslint-disable eqeqeq */
var testVar = "This should be 'let' or 'const'";
// eslint-disable-next-line no-undef
undefinedFunctionCall();
"hello world!" == "hello world"
登录后复制

You can also utilize the code editor integration to add these comments. With VS Code, you can right-click on ESLint errors or warnings and use the Quick Fix feature: ESLint adoption guide: Overview, examples, and alternatives

Rule suggestions and rule fixes

For a rule violation, your code editor may show a rule suggestion when you inspect the violation. In such a case, some problems reported by this rule are manually fixable by the code editor.

With the VS Code ESLint extension, you can do this from a context menu. When you browse through ESLint's Rules Reference, you can easily identify rules with suggestions by a bulb ? icon: ESLint adoption guide: Overview, examples, and alternatives Besides rule suggestions that require manual intervention of the developer to fix a violation, rule fixes safely correct violations automatically since they don't alter application logic. Every auto-fixable rule is marked with a wrench ? icon.

This feature is particularly useful for addressing common coding mistakes, formatting inconsistencies, and stylistic issues that adhere to predefined coding standards. To apply these automatic fixes, you can utilize the --fix option from the CLI:

$ npx eslint --fix
登录后复制

Later, we'll see how to establish a productive development workflow in your code editor to perform auto-fix on saving source files.

Utilizing shared community configurations

ESLint has a large community offering many publicly available configurations you can integrate via npm. These shared npm packages can contain one or more of the following concepts: configuration, rules, plugins, processors, and parsers. Here's how these concepts correlate:

  • Configuration — The entire eslint.config file represents an ESLint configuration
  • Rules — As covered in great detail above, shared rules are individual coding guidelines provided by the community, such as ESLint Config for standardjs.com
  • Processors — Processors are required to extract JavaScript code from other kinds of files before linting (e.g., code inside of script tag in .vue files)
  • Parsers — ESLint works internally with an Abstract Syntax Tree (AST) to statically lint source code. Custom parsers extend ESLint beyond the default parser (Espree) to support more JS language extensions (e.g., @typescript-eslint/parser to let ESLint understand TypeScript code)
  • Plugins — Custom plugins extend ESLint's capabilities by bundling additional rules, custom configurations, custom parsers, and preprocessors. The official ESLint plugin for Vue provides Vue-specific rules and internally uses vue-eslint-parser to process .vue files

Over the years, many popular and widespread shared configurations have been developed. However, with every breaking change in ESLint, the community projects need to migrate. Therefore, it's important to check the compatibility with ESLint v9 support and flat config support in particular before using a third-party npm package: ESLint adoption guide: Overview, examples, and alternatives To use a shared ruleset, you can also leverage the CLI option --config. The following installs a third-party configuration, eslint-config-canonical:

$ npm init @eslint/config@latest -- --config eslint-config-canonical
登录后复制

Let's look at an example to install a shared plugin. To add Vue support, we have to install eslint-plugin-vue:

$ npm i -D eslint-plugin-vue
登录后复制

The following eslint.config integrates the recommended ESLint rules in addition to the recommended configuration of eslint-plugin-vue. Further, it overrides one of the available Vue rules:

// eslint.config.js
import pluginJs from "@eslint/js";
import pluginVue from "eslint-plugin-vue";
export default [
  { rules: pluginJs.configs.recommended.rules },
  ...pluginVue.configs["flat/recommended"],
  {
    // override default rule settings
    rules: {
      // change severity to warning
      "vue/no-reserved-props": "warn"
    },
  },
];
登录后复制

If you inspect pluginVue.configs["flat/recommended"], you find out that internally the plugin uses a dedicated processor and parser:

//...
module.exports = [
  // ...
  {
    name: 'vue:base:setup-for-vue',
    files: ['*.vue', '**/*.vue'],
    plugins: {
      // ...
    },
    languageOptions: {
      parser: require('vue-eslint-parser'),
      sourceType: 'module',
      globals: globals.browser
    },
    rules: {
      'vue/comment-directive': 'error',
      'vue/jsx-uses-vars': 'error'
    },
    processor: 'vue/vue'
  }
]
登录后复制

The ESLint config inspect also shows this fact for the entry vue:base:setup-for-vue: ESLint adoption guide: Overview, examples, and alternatives

Further reading:

  • Reduce maintenance effort with shared ESLint and Prettier configs

Use cases for ESLint

This section explains a couple of use cases of using ESLint in projects.

Auto-fix ESLint issues on file save

Besides using the CLI option --fix, you can execute auto-fix from your code editor when you save a file. Then, all fixable rule violations in the file are automatically solved. This has multiple advantages:

  • Immediate feedback and correction — Helps you learn and adhere to coding standards more quickly, as you see the consequences of your actions immediately
  • Increased productivity — This workflow reduces the need to manually run ESLint from the CLI, which saves time and allows you to focus more on coding rather than fixing linting issues
  • Consistent code quality — By fixing issues as soon as they are introduced, you maintain a higher level of code quality throughout the development process. This approach helps prevent the accumulation of linting errors, making it easier to manage and review code
  • Reduced context switching — Reduces the need to switch between your editor and the terminal to run ESLint commands, helping you maintain your focus

This workflow is also very handy if you integrate ESLint with code formatting.

Further reading:

  • Reduce maintenance effort with shared ESLint and Prettier configs

Handle code formatting issues

As already mentioned, the ESLint team has deprecated all formatting rules and recommends only using logical rules. You can still use these stylistic rules, although their usage is discouraged.

A better approach is to choose one of the two options to enable ESLint supporting code formatting.

The common approach is to integrate ESLint with dedicated code formatting tools, such as Prettier or dprint. For Prettier, the preferred way is to run Prettier as an ESLint rule with eslint-plugin-prettier.

The following steps are required to set this up. First, install all dependencies:

$ npm i -D eslint@latest @eslint/js globals eslint-plugin-prettier eslint-config-prettier prettier
登录后复制

Then, use the plugins in eslint.config.mjs:

import pluginJs from "@eslint/js";
import pluginPrettierRecommended from "eslint-plugin-prettier/recommended";
export default [
  {
    name: "ESLint recommended config",
    ...pluginJs.configs.recommended,
  },
  {
    name: "ESLint plugin for Prettier formatting",
    ...pluginPrettierRecommended,
  },
];
登录后复制

Next, the IDE integration is required. For VS Code, make sure to install the extensions for ESLint and Prettier.

Lastly, we need to configure the format on save for VS Code in .vscode/settings.json:

{
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit"
  }
}
登录后复制

The npm package eslint-config-prettier eventually disables any ESLint rules dealing with code formatting to avoid conflicts with Prettier. You can see this with the handy ESLint Config Inspector: ESLint adoption guide: Overview, examples, and alternatives The second option is to use ESLint Stylistic. The primary focus of this project is on all stylistic rules including code formatting. This project was initiated as ESLint and typescript-eslint teams decided to deprecate formatting/stylistic-related rules.

The following steps are required to use ESLint Stylistic:

$ npm i -D @stylistic/eslint-plugin-js
登录后复制

Then you need to include the plugin into your eslint.config:

import pluginJs from "@eslint/js";
import stylisticJs from "@stylistic/eslint-plugin-js";
export default [
  {
    name: "logical rules only",
    ...pluginJs.configs.recommended,
  },
  {
    plugins: {
      "@stylistic/js": stylisticJs,
    }
  }
];
登录后复制

Finally, you need the same .vscode/settings.json as explained above if you want to use the plugin with auto-fixing stylistic issues on save: ESLint adoption guide: Overview, examples, and alternatives

Further reading:

  • Reduce maintenance effort with shared ESLint and Prettier configs

Using ESLint with Git hooks and in CI/CD pipelines

Using ESLint with Git commit hooks (with the help of tools like Husky and lint-staged) and within CI/CD pipelines serves complementary purposes to ensure code quality and consistency throughout the development lifecycle.

Integrating ESLint with Git commit hooks ensures that code is automatically linted before it is committed. This helps with catching and fixing linting errors early in the development process, preventing problematic code from entering the codebase. Tools like lint-staged help you to run ESLint only on changed files to improve DX.

As another safety net, you should also integrate ESLint into your CI/CD pipeline. In this section, we discussed how to integrate ESLint into your IDE, which means that ESLint runs on the current file you're working on. In your CI/CD environment, you should lint all your files for every pipeline run.

Further reading:

  • Build a robust React app with Husky pre-commit hooks and GitHub Actions
  • Developing an effective CI/CD pipeline for frontend apps

ESLint and its competitors

ESLint has been around for over 10 years. Over the years, there have been many competitors who have gradually lost favor with users. This section provides an overview of the field and how ESLint compares to its competitors.

第一代 linter

作为最早的 JavaScript linting 工具之一,JSLint 被誉为 JavaScript linting 的鼻祖。它自以为是,不支持自定义规则配置,设定了严格的编码标准,不允许有偏差。

JSHint 作为 JSLint 的一个分支出现,旨在为开发人员提供更多配置选项。尽管如此,它仍然不如 ESLint 灵活,特别是在规则定制和插件支持方面,限制了它对不同项目需求的适应性。上次发布可以追溯到 2022 年。

最初是 TypeScript 的首选 linting 工具,TSLint 自 2019 年起已被弃用,取而代之的是 ESLint,ESLint 扩展了其功能,通过插件包含 TypeScript。 TSLint 的弃用标志着 TypeScript 社区向更统一的 linting 解决方案的重大转变。

ESLint 在第一代同行中脱颖而出,自 2013 年以来已成为 JavaScript 生态系统中的主导工具。它的成功归功于其广泛的可配置性、插件生态系统以及对自定义规则的支持,使其适用于广泛的环境编码风格和项目要求。

第二代 linter(2020 年后)

JavaScript linting 工具的格局已经从第一代更加固执和僵化的工具发展到第二代注重性能且更易于访问的工具。

作为这些新短绒的一部分,Biome 在 2020 年大流行之后出现,但名称为 Rome。 Biome 于 2023 年中期创建,作为 Rome 的一个分支,这是一个得到不断发展的社区支持的活跃项目。 Biome 专注于更广泛的范围,除了 linting 之外还包括代码格式化。关于 linting,语言支持尚未与 ESLint 相提并论。

quick-lint-js 于 2021 年推出,承诺增强开发人员工作流程,将自己定位为 ESLint 的补充工具。它专为“实时速度”而设计,可在代码编辑器中提供快速反馈,无延迟。该工具的另一个目标是零配置,因此它是固执己见的。该工具针对特定目标群体。

RSLint 是一个相对较新的参与者,专注于提供零配置的 linting 工具。它正处于早期开发阶段,尚未准备好投入生产。最新版本是 2022 年发布的,因此尚不清楚开发是否仍在进行中。

从 2023 年 2 月开始,oxlint 并不是要取代 ESLint,而是要对其进行补充,特别是在 ESLint 的性能可能成为瓶颈的场景中。支持JavaScript、TypeScript和一些框架;例如,Vue.js。

作为 Deno 运行时的 linter, deno lint 原生支持 JavaScript 和 TypeScript。它与 Deno 的集成使其与其他产品区分开来,专门针对利用该运行时的项目。

虽然 ESLint 仍然是 JavaScript linting 的基石,但新工具的出现反映了社区对效率、性能和特定项目需求适应性的持续探索。第二代的影响仍在不断显现,许多工具找到了自己的定位或成为 ESLint 综合功能的宝贵补充。

比较表:ESLint 与其他 linter

下表将 ESLint 与其当前竞争对手进行了比较:

ESLint JSHint Biome quick-lint-js RSLint oxlint deno lint
Available since 2013 2010 2023 (Rome 2010) 2020 2020 2022 2020
Underlying technology JS (rewrite w/ Rust announced) JS Rust (Rome: JS) C++ Rust Rust Rust / TS
License MIT MIT MIT free GPL v3 MIT MIT MIT
Average releases per year 30 5 60 20 2 45 (parent project oxc) 20
npm downloads per week 38M 565K 531K 650 - 63K -
GitHub stars 24.6K 9K 12.7K 1.5K 2.7K 9.8K 1.5K
Mentioned in any year of State of JS
TS support
JSX support ✅ w/ [JSXHint](https://github.com/CondeNast/JSXHint)
Vue.js support
CSS support
Supports code formatting
VS Code integration
IntelliJ integration
Latest version 9.7.0 2.13.6 1.8.3 3.2.0 0.3.2 0.6.0 0.60.1
Configurability extensive minimal advanced zero zero advanced (ESLint v8 config scheme) minimal
Third-party plugin support
Third-party rules

我的印象是,ESLint 团队认真对待了一些批评,并在版本 9 中解决了它们——例如,更明智的默认选项来抵消配置的需要。最近发布的博客文章证实了我的观点,因为 ESLint 的核心仍然需要进行重大的架构更改,这可能会进一步提高性能。

像 Biome 这样的项目无疑是 ESLint 团队决定进行这些复杂改编的原因之一。竞争对手给出的一些关于为什么他们自己的解决方案比 ESLint 更好的理由已经过时了。

结论

您应该坚持使用 ESLint 作为您选择的 linting 工具吗?我建议在大多数用例中使用 ESLint,尤其是在商业环境中。 ESLint 被广泛采用,并且由于其广泛的分布,开发人员很可能知道如何使用它。

即使是雄心勃勃的竞争对手项目也无法涵盖开发人员所需的所有用例。例如,截至 2024 年 7 月,Biome 尚未完全支持 CSS 或 Vue.js。社区中还有其他声音主张使用 ESLint 和 Prettier 作为 linting 和格式化的最佳组合。

对于 ESLint 的复杂性和性能一直存在批评。然而,开发团队的具体项目经验、非常好的文档和工具都是支持 ESLint 的很好的论据。

除非您想涵盖非常具体的用例,例如 IDE 中的实时反馈(这可以通过 fast-lint-js 实现),否则 ESLint 以其丰富的功能集涵盖了几乎所有相关的开发用例。


LogRocket:通过了解上下文更轻松地调试 JavaScript 错误

调试代码始终是一项乏味的任务。但你越了解自己的错误,就越容易纠正它们。

LogRocket 允许您以新的、独特的方式理解这些错误。我们的前端监控解决方案跟踪用户与 JavaScript 前端的互动,使您能够准确查看用户的操作导致了错误。

ESLint adoption guide: Overview, examples, and alternatives

LogRocket 记录控制台日志、页面加载时间、堆栈跟踪、带有标头 + 正文的慢速网络请求/响应、浏览器元数据和自定义日志。了解 JavaScript 代码的影响从未如此简单!

免费试用。

以上是ESLint 采用指南:概述、示例和替代方案的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板