Heim > Web-Frontend > js-Tutorial > Hauptteil

ESLint-Einführungsleitfaden: Überblick, Beispiele und Alternativen

WBOY
Freigeben: 2024-08-08 22:30:52
Original
376 Leute haben es durchsucht

Geschrieben von Sebastian Weber✏️

ESLint ist seit vielen Jahren der De-facto-Standard für das Linting von JavaScript- und TypeScript-Projekten. Dieser Einführungsleitfaden erklärt, warum dies auch im Jahr 2024 immer noch der Fall ist.

Dieser Artikel behandelt die aktuelle Version von ESLint, die zum Zeitpunkt des Schreibens im Sommer 2024 verfügbar war (v9.7). Daher werden nur die Konzepte und Funktionen von Version 9 beschrieben, die im Vergleich zu den Vorgängerversionen einige wesentliche Änderungen mit sich bringt.

Wenn Sie ältere Versionen ohne die neueste Konfigurationsvariante mit flachen Konfigurationsdateien verwenden möchten, können Sie den offiziellen Migrationsleitfaden konsultieren.

Was ist ESLint?

ESLint ist ein konfigurierbarer und erweiterbarer JavaScript-Linter zur Durchführung statischer Codeanalysen. Es hilft Ihnen, Probleme in Ihrem Quellcode zu verfolgen und zu lösen, ohne ihn ausführen zu müssen. Die Probleme können alles Mögliche sein, von potenziellen Laufzeitfehlern über fehlerhafte Codierungspraktiken bis hin zu Codeformatierungsproblemen.

Als Software-Qualitätstool zielt ESLint darauf ab, Code konsistenter und robuster zu machen. Es überprüft Ihren Code mithilfe von Behauptungen, sogenannten Lint-Regeln, wie Ihr Code aussehen oder sich verhalten soll. Mit der Regel „no-use-before-define“ können Sie ESLint beispielsweise anweisen, Verstöße zu melden, wenn es auf Funktionsaufrufe stößt, bevor diese deklariert werden.

Darüber hinaus kann für jede Regel die Schwere der Verstöße als Warnung oder Fehler angegeben werden. Dadurch könnte in einer CI/CD-Pipeline ein Linting-Schritt bei gemeldeten Fehlern fehlschlagen, was auf ein größeres Problem hinweist, das untersucht werden muss.

ESLint kann mit Hilfe von Parsern und Plugins so konfiguriert werden, dass es TypeScript- oder JavaScript-Syntaxerweiterungen wie JSX oder die Konzepte von JavaScript-Frameworks wie React oder Vue versteht und lintet.

Warum wurde ESLint erstellt?

Die Idee zu ESLint entstand aufgrund der Unzulänglichkeiten der damals verfügbaren Linting-Tools wie JSCS, JSLint und JSHint. Diese Tools waren in ihren Regelsätzen und Konfigurationsmöglichkeiten etwas starr, was es schwierig machte, Regeln entsprechend den spezifischen Projektanforderungen anzupassen.

Seit der ersten Version von ESLint bilden Regeln das Rückgrat von ESLint. Sie bieten möglicherweise Vorschläge zur manuellen Behebung von Verstößen an, die direkt an den problematischen Codepositionen in Code-Editoren mit Markierungen und Überlagerungen angezeigt werden.

Darüber hinaus können Regeln Korrekturen bereitstellen, die es ESLint ermöglichen, Verstöße von CLI oder Ihrem Code-Editor automatisch zu beheben; z. B. Refactoring Ihrer Pfeilfunktion in eine implizite Rückgabevariante.

Neben einem viel besseren Linting-Erlebnis mit breiterer Tool- und Sprachunterstützung war und ist ein weiteres Verkaufsargument von ESLint die steckbare Architektur. Es ermöglicht eine größere Erweiterbarkeit und Anpassbarkeit als seine Konkurrenten und ermöglicht Entwicklern die Erstellung und gemeinsame Nutzung benutzerdefinierter Regeln sowie die Erweiterung von ESLint über seine Kernfunktionalität hinaus.

Ein Beweis für den Aufstieg von ESLint im Laufe der Jahre ist die Fusion mit JSCS, das im Laufe der Zeit an Boden verlor. Seit seiner Gründung hat sich ESLint erheblich weiterentwickelt:

  • ES6 und höher – ESLint hat seinen Regelsatz kontinuierlich aktualisiert, um neue ECMAScript-Standards zu berücksichtigen und die neuesten JavaScript-Funktionen und Syntaxerweiterungen nativ zu unterstützen, wie z. B. JSX. Sie können ESLint mithilfe verwandter Projekte auch erweitern, um andere Sprachen zu verstehen. z. B. typescript-eslint zur Unterstützung von TypeScript
  • Integration und Ökosystem – Das Tool wurde besser in verschiedene Entwicklungsumgebungen, Build-Tools (z. B. ESLint-Plugin für Prettier-Formatierung) und Code-Editoren (z. B. ESLint VS Code-Erweiterung) integriert. Die Community hat eine breite Palette von Plugins für verschiedene Bibliotheken und Frameworks beigesteuert (z. B. das offizielle ESLint-Plugin für Vue.js), um die Einzeldateikomponenten von Vue zu unterstützen, wodurch ESLint in verschiedenen JavaScript-Ökosystemen vielseitig einsetzbar ist
  • Leistungsverbesserungen – ESLint hat im Laufe der Zeit erhebliche Leistungsverbesserungen vorgenommen, wodurch die Analyse großer Codebasen schneller wird.

Wenn es um die Aufrechterhaltung der Codequalität und -konsistenz in JavaScript-Projekten geht, sticht ESLint als erstklassiges Tool hervor. Die Übernahme in Ihre Projekte kann die DX erheblich verbessern und sicherstellen, dass Ihre Codebasen sauber, lesbar und fehlerfrei bleiben.

ESLint wird mit vielen Regeln geliefert, die leicht an die Anforderungen eines Projekts angepasst werden können. Mithilfe von Community-Plugins können Sie sogar weitere Regeln hinzufügen. Darüber hinaus können Parser verwendet werden, um die Funktionalität von ESLint zu erweitern.

Weiterführende Literatur:

  • Verwendung von Prettier und ESLint für die JavaScript-Formatierung

Verwendung von ESLint

Bevor wir uns mit den Kernkonzepten und Funktionen von ESLint befassen können, müssen wir zunächst den ESLint-Workflow einrichten.

ESLint zu Ihrem Projekt hinzufügen

In einem Ordner mit einer vorhandenen package.json können Sie den folgenden Befehl ausführen, um ESLint zu Ihrem Entwicklungsprojekt hinzuzufügen. ESLint soll lokal installiert werden. Mit dem folgenden Befehl können Sie eine interaktive Installationsanleitung ausführen, die die Standard-ESLint-Konfiguration hinzufügt:

# run at root level of your project
$ npm init @eslint/config@latest
Nach dem Login kopieren

Sie können Ihr Projekt auch mit einer gemeinsam nutzbaren Konfiguration starten. Viele davon können Sie finden, indem Sie eine Github-Suche durchführen. Die Namenskonvention besteht darin, benutzerdefinierte Konfigurationen mit eslint-config- zu beginnen.

Der Installationsassistent stellt Ihnen ein paar Fragen zu Ihrem aktuellen Projekt-Setup: ESLint adoption guide: Overview, examples, and alternatives Nach Abschluss der Installation erstellte ESLint eine Konfigurationsdatei mit einem Dateisuffix, das vom Typ der von Ihnen gewählten Modulvariante abhängt. Für ESM finden Sie eine eslint.config.mjs in Ihrem Arbeitsverzeichnis. Konventionell gibt das Dateipräfix .mjs an, dass Ihre Projekte mit ESM funktionieren, aber eslint.config.js hätte den gleichen Effekt.

Arbeiten mit der flachen Konfiguration von ESLint

Diese sogenannte flache Konfiguration für ein Vanilla-JavaScript-Projekt sieht zunächst so aus:

// eslint.config.mjs
import globals from "globals";
import pluginJs from "@eslint/js";
export default [
  { languageOptions: { globals: globals.browser } },
  pluginJs.configs.recommended,
];
Nach dem Login kopieren

Mit dieser Konfiguration oben wird das Standard-ESLint-JavaScript-npm-Paket @eslint/js mit einer Browserumgebung (globals.browser) und allen empfohlenen JS-Regeln verwendet. Erstellen wir eine einfache JavaScript-Datei mit einigen Regelverstößen:

// playground.js
var testVar = "This should be 'let' or 'const'";
undefinedFunctionCall();
Nach dem Login kopieren

Wir nutzen die ESLint-CLI mit npx aus demselben Pfad, in dem sich eslint.config.mjs befindet:

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

In diesem Beispiel hat ESLint zwei Fehler aufgrund eines Verstoßes gegen die Regeln no-unused-vars und no-undef gemeldet: ESLint adoption guide: Overview, examples, and alternatives Das ESLint-GitHub-Projekt ist in einem Monorepo organisiert, und Sie können weitere Konfigurationsoptionen einsehen, indem Sie sich das ansehen das @eslint/js-Paket. Die obige Konfiguration fügt alle empfohlenen Regeln hinzu, die alle einen Fehlerschweregrad aufweisen. Wir erfahren gleich mehr über die Schwere des Verstoßes.

Die folgende Konfiguration zeigt verschiedene Varianten der Verwendung der empfohlenen Regeln:

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",
    },
  }
];
Nach dem Login kopieren

Das folgende Snippet zeigt, dass ESLint standardmäßige JavaScript-Regeln liefert, da Sie sie verwenden können, ohne etwas zu importieren, wenn Sie den Namen kennen. Dies wird jedoch nicht empfohlen:

import globals from "globals";
export default [
  { languageOptions: { globals: globals.browser } },
  {
    rules: {
      "no-unused-vars": "warn",
    },
  },
];
Nach dem Login kopieren

Integration von ESLint in Ihren Code-Editor

Es gibt eine Vielzahl von Möglichkeiten, ESLint in Toolketten, Editoren und IDEs zu integrieren. Wenn Sie möchten, dass VS Code Regelverstöße in Ihren Quelldateien hervorhebt, müssen Sie lediglich die offizielle ESLint-Erweiterung installieren: ESLint adoption guide: Overview, examples, and alternatives Wenn Sie sich jemals in einer Situation befinden, in der die ESLint-Erweiterung in VS Code nicht auf Ihre Konfigurationsänderungen reagiert , hilft Ihnen normalerweise eine der folgenden Optionen weiter.

Werfen Sie zunächst einen Blick in das Ausgabefenster von VS Code, wählen Sie ESLint aus der Dropdown-Liste aus und suchen Sie nach einem Fehler: ESLint adoption guide: Overview, examples, and alternatives Zweitens starten Sie den internen ESLint-Server mithilfe der Befehlspalette neu und führen Sie ESLint aus: ESLint-Server neu starten .

TypeScript-Unterstützung hinzufügen

Wenn Sie im interaktiven Installationshandbuch TypeScript auswählen, verwendet die Konfiguration typescript-eslint, um ESLint beizubringen, wie TypeScript interpretiert wird. Sie können die TypeScript-Unterstützung auch manuell installieren. Stellen Sie sicher, dass Sie die richtige Version (≥ v8.0.0-alpha.10) installieren, die mit ESLint v9 und Flat Config kompatibel ist:

$ npm i -D eslint @eslint/js @types/eslint__js typescript typescript-eslint@8.0.0-alpha.10 --force
Nach dem Login kopieren

Mit der folgenden Konfiguration verwenden Sie die empfohlenen JavaScript-Regeln von ESLint in Kombination mit den empfohlenen TypeScript-Regeln, die von typescript-eslint bereitgestellt werden:

// eslint.config.mjs
import eslint from "@eslint/js";
import tseslint from "typescript-eslint";
export default tseslint.config(
  eslint.configs.recommended,
  ...tseslint.configs.recommended
);
Nach dem Login kopieren

Der nächste Screenshot zeigt, dass sowohl npx eslint als auch die VS Code ESLint-Erweiterung JS- und TS-Verstöße melden: ESLint adoption guide: Overview, examples, and alternatives

Wichtige ESLint-Konzepte und -Funktionen, die Sie kennen sollten

Der vorherige Abschnitt gab einen praktischen Einblick in die Einrichtung und Verwendung von ESLint. Im Folgenden gehe ich auf die Kernkonzepte ein, die Sie verstehen müssen, um ESLint gewinnbringend einzusetzen.

Mehr zur flachen Konfiguration

Mit dem neuen Flat-Config-Konzept ist die gesamte Projektkonfiguration Teil einer einzigen eslint.config.js(c|j|m)-Datei. Bisher konnte die Konfiguration auf mehrere .eslintrc-Dateien verteilt sein und sogar Teil von package.json sein, was zu Komplexität und Verwirrung führte.

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'
  },
},
Nach dem Login kopieren

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
Nach dem Login kopieren

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,
    },
  },
  // ...
];
Nach dem Login kopieren

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,
  },
];
Nach dem Login kopieren

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;
}
Nach dem Login kopieren

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"
Nach dem Login kopieren

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
Nach dem Login kopieren

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
Nach dem Login kopieren

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
Nach dem Login kopieren

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"
    },
  },
];
Nach dem Login kopieren

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'
  }
]
Nach dem Login kopieren

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
Nach dem Login kopieren

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,
  },
];
Nach dem Login kopieren

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"
  }
}
Nach dem Login kopieren

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
Nach dem Login kopieren

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,
    }
  }
];
Nach dem Login kopieren

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.

Die erste Generation von Linters

JSLint wurde als eines der ersten Linting-Tools für JavaScript eingeführt und gilt als Urvater der JavaScript-Linters. Es ist sehr eigensinnig und unterstützt keine benutzerdefinierte Regelkonfiguration, wodurch ein strenger Codierungsstandard ohne Spielraum für Abweichungen festgelegt wird.

JSHint entstand als Fork von JSLint und wurde eingeführt, um Entwicklern mehr Konfigurationsoptionen zu bieten. Dennoch bleibt es weniger flexibel als ESLint, insbesondere im Hinblick auf die Regelanpassung und Plugin-Unterstützung, was seine Anpassungsfähigkeit an unterschiedliche Projektanforderungen einschränkt. Die letzte Veröffentlichung stammt aus dem Jahr 2022.

TSLint war ursprünglich das bevorzugte Linting-Tool für TypeScript und wurde 2019 zugunsten von ESLint veraltet, das seine Funktionen durch Plugins um TypeScript erweiterte. Die Abschaffung von TSLint markierte einen bedeutenden Wandel in der TypeScript-Community hin zu einer einheitlicheren Linting-Lösung.

ESLint sticht unter seinen Mitbewerbern der ersten Generation hervor und hat sich seit 2013 zum dominierenden Tool im JavaScript-Ökosystem entwickelt. Sein Erfolg ist auf seine umfassende Konfigurierbarkeit, das Plugin-Ökosystem und die Unterstützung benutzerdefinierter Regeln zurückzuführen, wodurch es an ein breites Spektrum anpassbar ist von Codierungsstilen und Projektanforderungen.

Zweite Linter-Generation (nach 2020)

Die Landschaft der JavaScript-Linting-Tools hat sich erheblich weiterentwickelt, von den eigensinnigeren und strengeren Tools der ersten Generation zu den leistungsorientierten und zugänglicheren Tools der zweiten Generation.

Als Teil dieser neuen Linters entstand Biome im Zuge der Pandemie im Jahr 2020, allerdings unter dem Namen Rome. Biome wurde Mitte 2023 als Fork of Rome gegründet, einem aktiven Projekt, das von einer wachsenden Community unterstützt wird. Biome konzentriert sich auf einen breiteren Bereich, einschließlich der Codeformatierung zusätzlich zum Linting. Bezüglich Linting ist die Sprachunterstützung noch nicht auf dem Niveau von ESLint.

Quick-lint-js wurde 2021 mit dem Versprechen eingeführt, den Entwickler-Workflow zu verbessern, und positioniert sich als ergänzendes Tool zu ESLint. Es ist auf „Echtzeitgeschwindigkeit“ ausgelegt und bietet schnelles Feedback innerhalb Ihres Code-Editors ohne Latenz. Ein weiteres Ziel des Tools ist Zero-Config, daher ist es eigensinnig. Das Tool richtet sich an eine bestimmte Zielgruppe.

RSLint ist ein relativ neuer Anbieter und konzentriert sich auf die Bereitstellung eines Linting-Tools ohne Konfiguration. Es befindet sich in einem frühen Entwicklungsstadium und ist noch nicht produktionsreif. Die letzte Veröffentlichung stammt aus dem Jahr 2022, daher ist unklar, ob die Entwicklung noch aktiv ist.

Ab Februar 2023 soll oxlint ESLint nicht ersetzen, sondern ergänzen, insbesondere in Szenarien, in denen die Leistung von ESLint einen Engpass darstellen könnte. Es unterstützt JavaScript, TypeScript und einige Frameworks; z. B. Vue.js.

Als Linter für die Deno-Laufzeit unterstützt deno lint nativ JavaScript und TypeScript. Durch die Integration mit Deno hebt es sich vom Rest ab und ist speziell auf Projekte zugeschnitten, die diese Laufzeit nutzen.

Während ESLint ein Eckpfeiler des JavaScript-Lintings bleibt, spiegelt das Aufkommen neuer Tools das ständige Streben der Community nach Effizienz, Leistung und Anpassungsfähigkeit an spezifische Projektanforderungen wider. Die Auswirkungen dieser zweiten Generation sind noch nicht ausgeschöpft, und viele Tools finden ihre Nische oder dienen als wertvolle Ergänzung zu den umfassenden Funktionen von ESLint.

Vergleichstabelle: ESLint vs. andere Linters

Die folgende Tabelle vergleicht ESLint mit seinen aktuellen Konkurrenten:

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

Ich hatte den Eindruck, dass das ESLint-Team einige der Kritikpunkte ernst genommen und mit Version 9 behoben hat – z. B. sinnvollere Standardoptionen, um dem Konfigurationsbedarf entgegenzuwirken. Der kürzlich veröffentlichte Blog-Beitrag bestätigt meinen Standpunkt, da am ESLint-Kern noch große architektonische Änderungen vorgenommen werden müssen, die vermutlich die Leistung weiter verbessern werden.

Projekte wie Biome sind sicherlich ein Grund, warum sich das ESLint-Team für diese komplexen Anpassungen entschieden hat. Einige der von Wettbewerbern genannten Gründe, warum ihre eigene Lösung besser als ESLint ist, sind bereits veraltet.

Abschluss

Sollten Sie sich an ESLint als Linting-Tool Ihrer Wahl halten? Ich empfehle die Verwendung von ESLint in den meisten Anwendungsfällen, insbesondere in einer kommerziellen Umgebung. ESLint ist gut angenommen und Entwickler wissen aufgrund der weiten Verbreitung höchstwahrscheinlich, wie man es verwendet.

Selbst die ambitionierten Konkurrenzprojekte können noch nicht alle Anwendungsfälle abdecken, die Entwickler benötigen. Beispielsweise unterstützt Biome seit Juli 2024 weder CSS noch Vue.js vollständig. Es gibt auch andere Stimmen aus der Community, die sich für die Verwendung von ESLint mit Prettier als beste Kombination für Linting und Formatierung aussprechen.

Es gab schon immer Kritik an der Komplexität und Leistung von ESLint. Allerdings sind konkrete Projekterfahrungen in Entwicklungsteams, die sehr gute Dokumentation und das Tooling sehr gute Argumente für ESLint.

Sofern Sie nicht einen ganz bestimmten Anwendungsfall abdecken möchten, wie z. B. Echtzeit-Feedback in der IDE (was mit quick-lint-js möglich ist), deckt ESLint mit seinem umfangreichen Funktionsumfang praktisch alle relevanten Entwicklungsanwendungsfälle ab.


LogRocket: JavaScript-Fehler einfacher beheben, indem Sie den Kontext verstehen

Das Debuggen von Code ist immer eine mühsame Aufgabe. Aber je besser Sie Ihre Fehler verstehen, desto einfacher ist es, sie zu beheben.

LogRocket ermöglicht es Ihnen, diese Fehler auf neue und einzigartige Weise zu verstehen. Unsere Frontend-Überwachungslösung verfolgt die Benutzerinteraktion mit Ihren JavaScript-Frontends, um Ihnen die Möglichkeit zu geben, genau zu sehen, was der Benutzer getan hat, was zu einem Fehler geführt hat.

ESLint adoption guide: Overview, examples, and alternatives

LogRocket zeichnet Konsolenprotokolle, Seitenladezeiten, Stack-Traces, langsame Netzwerkanfragen/-antworten mit Headern + Textkörpern, Browser-Metadaten und benutzerdefinierte Protokolle auf. Es wird nie einfacher sein, die Auswirkungen Ihres JavaScript-Codes zu verstehen!

Probieren Sie es kostenlos aus.

Das obige ist der detaillierte Inhalt vonESLint-Einführungsleitfaden: Überblick, Beispiele und Alternativen. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!