ホームページ  >  記事  >  ウェブフロントエンド  >  ESLint 導入ガイド: 概要、例、代替案

ESLint 導入ガイド: 概要、例、代替案

WBOY
WBOYオリジナル
2024-08-08 22:30:52383ブラウズ

セバスチャン・ウェバー著✏️

長年にわたり、ESLint は JavaScript および TypeScript プロジェクトの lint を実行するための事実上の標準でした。この導入ガイドでは、これが 2024 年も依然として当てはまる理由を説明します。

この記事では、2024 年夏の執筆時点で利用可能だった ESLint の現在のバージョン (v9.7) について説明します。したがって、以前のバージョンと比較していくつかの重大な破壊的変更をもたらす v9 の概念と機能のみについて説明します。

フラット構成ファイルで最新の構成フレーバーを持たない古いバージョンを使用したい場合は、公式移行ガイドを参照してください。

ESLintとは何ですか?

ESLint は、静的コード分析を実行するための構成可能で拡張可能な JavaScript リンターです。ソース コードを実行することなく、ソース コード内の問題をトレースして解決するのに役立ちます。問題には、潜在的な実行時のバグから不適切なコーディング方法、コードのフォーマットの問題まで、さまざまなものが考えられます。

ESLint はソフトウェア品質ツールとして、コードの一貫性と堅牢性を高めることを目指しています。コードの外観や動作に関するアサーション、いわゆる lint ルールを利用してコードをチェックします。たとえば、ルール no-use-before-define を使用すると、関数呼び出しが宣言される前に関数呼び出しが発生した場合に違反を報告するように ESLint に指示できます。

さらに、ルールごとに違反の重大度を警告またはエラーに指定できます。そのため、CI/CD パイプラインでは、調査が必要なより大きな問題を示す報告されたエラーに対して lint ステップが失敗する可能性があります。

ESLint は、パーサーとプラグインを利用して、TypeScript や JSX などの JavaScript 構文拡張機能、または React や Vue などの JavaScript フレームワークの概念を理解して lint するように構成できます。

ESLint はなぜ作成されたのですか?

ESLint のアイデアは、JSCS、JSLint、JSHint など、当時利用可能なリンティング ツールが不十分だったことから生まれました。これらのツールはルール セットと構成機能がやや厳格で、特定のプロジェクト要件に応じてルールを調整することが困難でした。

ESLint の初期バージョン以来、ルールは ESLint のバックボーンを構築してきました。コード エディター内で問題のあるコードの位置にマーカーやオーバーレイを使用して直接表示される違反を手動で解決する方法に関する提案を提供する場合があります。

さらに、ルールは、ESLint が CLI またはコード エディターからの違反を自動的に解決できるようにする修正を提供する場合があります。たとえば、アロー関数を暗黙的な戻り値バリアントにリファクタリングします。

幅広いツールと言語のサポートによるはるかに優れた lint エクスペリエンスに加えて、ESLint のもう 1 つのセールス ポイントは、プラグ可能なアーキテクチャであり、今でもそうです。競合他社よりも優れた拡張性とカスタマイズ性を実現し、開発者がカスタム ルールを作成して共有し、コア機能を超えて ESLint を拡張できるようにします。

ESLint が長年にわたって台頭してきた証拠は、ESLint が時間の経過とともに失速していた JSCS と合併されたことです。 ESLint はその誕生以来、大きく進化してきました:

  • ES6 以降 — ESLint は、新しい ECMAScript 標準に対応するためにルール セットを継続的に更新し、JSX などの最新の JavaScript 機能と構文拡張機能をネイティブにサポートしています。関連プロジェクトの助けを借りて、ESLint を拡張して他の言語を理解することもできます。例: TypeScript
  • をサポートする typescript-eslint
  • 統合とエコシステム — このツールは、さまざまな開発環境、ビルド ツール (Prettier フォーマット用の ESLint プラグインなど)、およびコード エディター (ESLint VS Code 拡張機能など) との統合が改善されています。コミュニティは、Vue の単一ファイル コンポーネントをサポートするために、さまざまなライブラリやフレームワーク用の幅広いプラグイン (Vue.js 用の公式 ESLint プラグインなど) を提供し、ESLint をさまざまな JavaScript エコシステム間で多用途に使えるようにしました
  • パフォーマンスの向上 — ESLint は時間の経過とともにパフォーマンスが大幅に向上し、大規模なコードベースの分析がより速くなりました。

JavaScript プロジェクトでコードの品質と一貫性を維持するという点では、ESLint は最高のツールとして際立っています。これをプロジェクトに導入すると、DX が大幅に強化され、コードベースがクリーンで読みやすく、エラーがない状態を維持できます。

ESLint には、プロジェクトの要件に合わせて簡単に調整できる多くのルールが同梱されています。コミュニティ プラグインを使用してさらにルールを追加することもできます。さらに、パーサーを利用して ESLint の機能を拡張できます。

さらに読む:

  • JavaScript フォーマットに Prettier と ESLint を使用する

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.config.mjs が配置されている同じパスから npx を使用して ESLint CLI を利用します。

$ npx eslint # all files recursively
$ npx eslint playground.js # specific file(s)
$ npx eslint *.js # ESLint supports globs

この例では、ESLint はルール no-unused-vars と no-undef の違反により 2 つのエラーを報告しました: ESLint adoption guide: Overview, examples, and alternatives ESLint GitHub プロジェクトはモノリポジトリに編成されており、以下を調べることでより多くの構成オプションを参照できます。 @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 を実行します。 ESLint サーバーを再起動します.

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 を有益に使用するために理解する必要がある中心的な概念について説明します。

フラット構成の詳細

新しいフラット構成コンセプトでは、プロジェクト構成全体が 1 つの 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.

第一世代のリンター

JavaScript 用の最初の lint ツールの 1 つとして起動された JSLint は、JavaScript リンターの祖として知られています。これは非常に独自性が高く、カスタム ルール構成をサポートしておらず、逸脱の余地のない厳格なコーディング標準を設定しています。

JSLint のフォークとして登場した JSHint は、開発者により多くの構成オプションを提供するために導入されました。それにもかかわらず、特にルールのカスタマイズとプラグインのサポートの点で ESLint よりも柔軟性が低く、プロジェクトの多様なニーズへの適応性が制限されています。最後のリリースは 2022 年に遡ります。

当初 TypeScript の頼りになる lint ツールだった TSLint は、2019 年時点で非推奨となり、プラグインを通じて TypeScript を含めるように機能を拡張した ESLint が採用されました。 TSLint の非推奨は、より統合された lint ソリューションに向けた TypeScript コミュニティの大きな変化を示しました。

ESLint は、第 1 世代の他のツールの中でも際立っており、2013 年以来 JavaScript エコシステムの主要なツールとなっています。その成功の要因は、その広範な構成可能性、プラグイン エコシステム、カスタム ルールのサポートにより、幅広い範囲に適応できるようになっていることにあります。コーディング スタイルとプロジェクト要件について説明します。

第 2 世代のリンター (2020 年以降)

JavaScript lint ツールの状況は、第 1 世代のより独断的で厳格なツールから、第 2 世代のパフォーマンス重視でよりアクセスしやすいツールへと大幅に進化しました。

これらの新しいリンターの一部として、Biome は 2020 年のパンデミック後に出現しましたが、名前は Rome でした。 Biome は、ローマのフォークとして 2023 年半ばに設立されました。これは、成長するコミュニティによってサポートされているアクティブなプロジェクトです。 Biome は、lint に加えてコードのフォーマットなど、より広い範囲に焦点を当てています。 lint に関しては、言語サポートはまだ ESLint と同等ではありません。

開発者のワークフローを強化することを約束して 2021 年にリリースされた Quick-lint-js は、ESLint を補完するツールとしての地位を確立しています。 「リアルタイム速度」を重視して設計されており、コードエディター内で遅延なく迅速なフィードバックを提供します。このツールのもう 1 つの目標は設定不要であるため、意見が分かれています。このツールは特定のターゲット グループを対象としています。

比較的新しい参入者である RSLint は、設定不要の lint ツールの提供に重点を置いています。これは開発初期段階にあり、製品化の準備ができていません。最後のリリースは 2022 年であるため、開発がまだアクティブであるかどうかは不明です。

2023 年 2 月以降、oxlint は ESLint を置き換えることを目的としたものではなく、特に ESLint のパフォーマンスがボトルネックになる可能性があるシナリオでそれを補完することを目的としています。 JavaScript、TypeScript、およびいくつかのフレームワークをサポートしています。例: Vue.js。

Deno ランタイムのリンターとして、deno lint は JavaScript と TypeScript をネイティブにサポートします。 Deno との統合により、他のパックとは一線を画し、特にこのランタイムを利用するプロジェクトに対応します。

ESLint は依然として JavaScript lint の基礎ですが、新しいツールの出現は、効率、パフォーマンス、特定のプロジェクトのニーズへの適応性に対するコミュニティの継続的な探求を反映しています。この第 2 世代の影響の結果はまだ明らかになっておらず、多くのツールがそれぞれのニッチ分野を見つけたり、ESLint の包括的な機能の貴重な補完として機能したりしています。

比較表: ESLint と他のリンター

次の表は、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 チームがこれらの複雑な適応を決定した理由の 1 つであることは確かです。競合他社が独自のソリューションが ESLint よりも優れている理由として挙げた理由の一部は、すでに時代遅れになっています。

結論

リンティング ツールとして ESLint を選択する必要がありますか?ほとんどのユースケース、特に商用環境では ESLint を使用することをお勧めします。 ESLint はよく採用されており、広く配布されているため、開発者はおそらく ESLint の使用方法を知っています。

野心的な競合他社のプロジェクトであっても、開発者が必要とするすべてのユースケースをまだカバーすることはできません。たとえば、Biome は 2024 年 7 月の時点で CSS または Vue.js を完全にはサポートしていません。コミュニティからは、リンティングとフォーマットの最適な組み合わせとして ESLint と Prettier の使用を支持する声もあります。

ESLint の複雑さとパフォーマンスに関しては常に批判がありました。ただし、開発チームにおける具体的なプロジェクトの経験、その非常に優れたドキュメント、およびツールは、ESLint を支持する非常に良い議論になります。

IDE でのリアルタイム フィードバック (quick-lint-js で可能) など、非常に特殊なユースケースをカバーしたい場合を除き、ESLint はその豊富な機能セットで事実上すべての関連開発ユースケースをカバーします。


LogRocket: コンテキストを理解することで JavaScript エラーをより簡単にデバッグします

コードのデバッグは常に面倒な作業です。しかし、間違いを理解すればするほど、修正が容易になります。

LogRocket を使用すると、これらのエラーを新しい独自の方法で理解できます。当社のフロントエンド監視ソリューションは、JavaScript フロントエンドに対するユーザーの関与を追跡し、エラーを引き起こしたユーザーの行動を正確に確認できるようにします。

ESLint adoption guide: Overview, examples, and alternatives

LogRocket は、コンソール ログ、ページの読み込み時間、スタック トレース、ヘッダーと本文を含む遅いネットワーク リクエスト/レスポンス、ブラウザーのメタデータ、カスタム ログを記録します。 JavaScript コードの影響を理解するのがこれまでになく簡単になります!

無料でお試しください。

以上がESLint 導入ガイド: 概要、例、代替案の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。