Rumah  >  Artikel  >  hujung hadapan web  >  Panduan penggunaan ESLint: Gambaran keseluruhan, contoh dan alternatif

Panduan penggunaan ESLint: Gambaran keseluruhan, contoh dan alternatif

WBOY
WBOYasal
2024-08-08 22:30:52381semak imbas

Ditulis oleh Sebastian Weber✏️

Selama bertahun-tahun, ESLint telah menjadi standard de facto untuk menyelitkan projek JavaScript dan TypeScript. Panduan pengambilan anak angkat ini menerangkan sebab perkara ini masih berlaku untuk 2024.

Artikel ini merangkumi versi semasa ESLint, yang tersedia pada masa penulisan pada musim panas 2024 (v9.7). Oleh itu, hanya konsep dan ciri v9 yang diterangkan, yang membawa beberapa perubahan besar berbanding versi sebelumnya.

Jika anda ingin menggunakan versi lama tanpa rasa konfigurasi terbaharu dengan fail konfigurasi rata, anda boleh merujuk panduan migrasi rasmi.

Apakah ESLint?

ESLint ialah linter JavaScript yang boleh dikonfigurasikan dan boleh dipanjangkan untuk melaksanakan analisis kod statik. Ia membantu anda mengesan dan menyelesaikan masalah dalam kod sumber anda tanpa perlu melaksanakannya. Masalah boleh menjadi apa-apa daripada pepijat masa jalan yang berpotensi, dan amalan pengekodan yang buruk, kepada isu pemformatan kod.

Sebagai alat kualiti perisian, ESLint bertujuan untuk menjadikan kod lebih konsisten dan mantap. Ia menyemak kod anda dengan bantuan penegasan, yang dipanggil peraturan lint, mengenai cara kod anda sepatutnya kelihatan atau berkelakuan. Contohnya, dengan peraturan no-use-before-define, anda boleh mengarahkan ESLint untuk melaporkan pelanggaran apabila ia menghadapi panggilan fungsi sebelum ia diisytiharkan.

Selanjutnya, tahap keterukan pelanggaran boleh ditentukan untuk setiap peraturan sebagai amaran atau ralat. Oleh itu, dalam saluran paip CI/CD, langkah linting boleh gagal untuk ralat yang dilaporkan yang menunjukkan masalah yang lebih besar yang perlu disiasat.

ESLint, dengan bantuan penghurai dan pemalam, boleh dikonfigurasikan untuk memahami dan menyelitkan sambungan sintaks TypeScript atau JavaScript, seperti JSX, atau konsep rangka kerja JavaScript seperti React atau Vue.

Mengapa ESLint dicipta?

Idea ESLint timbul kerana ketidakcukupan alat linting yang tersedia pada masa itu, seperti JSCS, JSLint dan JSHint. Alat ini agak tegar dalam set peraturan dan keupayaan konfigurasi, menjadikannya sukar untuk melaraskan peraturan mengikut keperluan projek khusus mereka.

Sejak versi awal ESLint, peraturan telah membina tulang belakang ESLint. Mereka mungkin menawarkan cadangan tentang cara menyelesaikan pelanggaran secara manual yang ditunjukkan secara langsung pada kedudukan kod bermasalah dalam editor kod dengan penanda dan tindanan.

Selain itu, peraturan mungkin menyediakan pembetulan yang membolehkan ESLint menyelesaikan pelanggaran secara automatik daripada CLI atau editor kod anda; cth., memfaktorkan semula fungsi anak panah anda kepada varian pulangan tersirat.

Selain pengalaman linting yang lebih baik dengan sokongan alat dan bahasa yang lebih luas, satu lagi nilai jualan ESLint ialah seni bina boleh pasang. Ia membolehkan kebolehlanjutan dan kebolehubahsuaian yang lebih besar daripada pesaingnya yang membenarkan pembangun mencipta dan berkongsi peraturan tersuai serta melanjutkan ESLint melangkaui fungsi terasnya.

Bukti kenaikan ESLint selama ini ialah ia telah digabungkan dengan JSCS, yang semakin lemah dari semasa ke semasa. Sejak penubuhannya, ESLint telah berkembang dengan ketara:

  • ES6 dan seterusnya — ESLint sentiasa mengemas kini peraturannya yang ditetapkan untuk menampung piawaian ECMAScript baharu, memberikan sokongan untuk ciri JavaScript terkini dan sambungan sintaks secara asli, seperti JSX. Anda juga boleh melanjutkan ESLint untuk memahami bahasa lain dengan bantuan projek berkaitan; cth., typescript-eslint untuk menyokong TypeScript
  • Integrasi dan ekosistem — Alat ini telah menyaksikan penyepaduan yang lebih baik dengan pelbagai persekitaran pembangunan, alat binaan (cth., pemalam ESLint untuk pemformatan Prettier) dan editor kod (cth., sambungan ESLint VS Code). Komuniti telah menyumbangkan pelbagai pemalam untuk perpustakaan dan rangka kerja yang berbeza (cth., pemalam ESLint rasmi untuk Vue.js) untuk menyokong komponen fail tunggal Vue, menjadikan ESLint serba boleh merentas ekosistem JavaScript yang berbeza
  • Peningkatan prestasi — ESLint telah membuat peningkatan prestasi yang ketara dari semasa ke semasa, menjadikannya lebih pantas untuk menganalisis pangkalan kod yang besar.

Dalam hal mengekalkan kualiti dan ketekalan kod dalam projek JavaScript, ESLint menonjol sebagai alat utama. Mengguna pakainya ke dalam projek anda boleh meningkatkan DX dengan ketara, memastikan pangkalan kod anda kekal bersih, boleh dibaca dan bebas daripada ralat.

ESLint dihantar dengan banyak peraturan yang boleh diubah suai mengikut keperluan projek dengan mudah. Anda juga boleh menambah lebih banyak peraturan dengan bantuan pemalam komuniti. Selanjutnya, penghurai boleh digunakan untuk melanjutkan kefungsian ESLint.

Bacaan lanjut:

  • Menggunakan Prettier dan ESLint untuk pemformatan JavaScript

Menggunakan ESLint

Sebelum kita boleh mendalami konsep teras dan ciri ESLint, kita perlu menyediakan aliran kerja ESLint terlebih dahulu.

Menambah ESLint pada projek anda

Dalam folder dengan package.json sedia ada, anda boleh menjalankan arahan berikut untuk menambah ESLint pada projek dev anda. ESLint dimaksudkan untuk dipasang secara tempatan. Dengan arahan berikut, anda boleh menjalankan panduan pemasangan interaktif yang menambah konfigurasi ESLint lalai:

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

Anda juga boleh memulakan projek anda dengan konfigurasi boleh kongsi. Anda boleh menemui banyak daripada mereka dengan melakukan carian Github. Konvensyen penamaan adalah untuk memulakan konfigurasi tersuai dengan eslint-config-.

Wizard pemasangan bertanya kepada anda beberapa soalan tentang persediaan projek semasa anda: ESLint adoption guide: Overview, examples, and alternatives Selepas melengkapkan pemasangan, ESLint mencipta fail konfigurasi dengan akhiran fail bergantung pada jenis varian modul yang anda pilih. Untuk ESM, anda menemui eslint.config.mjs dalam direktori kerja anda. Sebagai konvensyen, awalan fail .mjs menunjukkan bahawa projek anda berfungsi dengan ESM tetapi eslint.config.js akan mempunyai kesan yang sama.

Bekerja dengan konfigurasi rata ESLint

Konfigurasi rata yang dipanggil ini untuk projek JavaScript vanila pada mulanya kelihatan seperti ini:

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

Dengan konfigurasi ini di atas, pakej npm JavaScript ESLint lalai @eslint/js digunakan dengan persekitaran penyemak imbas (globals.browser) dan semua peraturan JS yang disyorkan. Mari buat fail JavaScript mudah dengan beberapa pelanggaran peraturan:

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

Kami memanfaatkan ESLint CLI dengan npx dari laluan yang sama di mana eslint.config.mjs terletak:

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

Dalam contoh ini, ESLint melaporkan dua ralat akibat pelanggaran peraturan no-unused-vars dan no-undef: ESLint adoption guide: Overview, examples, and alternatives Projek ESLint GitHub disusun dalam monorepo dan anda boleh merujuk lebih banyak pilihan konfigurasi dengan melihat ke dalam pakej @eslint/js. Konfigurasi di atas menambah semua peraturan yang disyorkan, yang semuanya mempunyai tahap keterukan ralat. Kami akan mengetahui lebih lanjut tentang keterukan pelanggaran dalam satu minit.

Konfigurasi berikut menunjukkan variasi berbeza menggunakan peraturan yang disyorkan:

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",
    },
  }
];

Coretan berikut menunjukkan bahawa ESLint menghantar peraturan JavaScript di luar kotak kerana anda boleh menggunakannya tanpa mengimport apa-apa dengan mengetahui namanya. Walau bagaimanapun, ini tidak disyorkan:

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

Mengintegrasikan ESLint dengan editor kod anda

Terdapat pelbagai cara untuk menyepadukan ESLint ke dalam rangkaian alat, editor dan IDE. Jika anda mahu Kod VS menyerlahkan pelanggaran peraturan di dalam fail sumber anda, anda hanya perlu memasang sambungan ESLint rasmi: ESLint adoption guide: Overview, examples, and alternatives Jika anda pernah mendapati diri anda berada dalam situasi di mana sambungan ESLint dalam Kod VS tidak bertindak balas kepada perubahan konfigurasi anda , salah satu daripada pilihan berikut biasanya akan membantu anda.

Pertama, lihat panel keluaran Kod VS, pilih ESLint dari menu lungsur, dan cari ralat: ESLint adoption guide: Overview, examples, and alternatives Kedua, mulakan semula pelayan ESLint dalaman dengan bantuan palet arahan dan jalankan ESLint: Mulakan semula Pelayan ESLint .

Menambah sokongan TypeScript

Dengan panduan pemasangan interaktif, jika anda memilih TypeScript, konfigurasi menggunakan typescript-eslint untuk mengajar ESLint cara mentafsir TypeScript. Anda juga boleh memasang sokongan TypeScript secara manual. Pastikan anda memasang versi yang betul (≥ v8.0.0-alpha.10) yang serasi dengan ESLint v9 dan konfigurasi rata:

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

Dengan konfigurasi berikut, anda menggunakan peraturan JavaScript ESLint yang disyorkan dalam kombinasi dengan peraturan TypeScript yang disyorkan yang disediakan oleh typescript-eslint:

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

Tangkapan skrin seterusnya menunjukkan bahawa npx eslint serta sambungan VS Code ESLint kedua-duanya melaporkan pelanggaran JS dan TS: ESLint adoption guide: Overview, examples, and alternatives

Konsep dan ciri ESLint utama yang perlu diketahui

Bahagian sebelumnya memberikan pandangan langsung tentang cara ESLint disediakan dan digunakan. Dalam perkara berikut, saya akan membincangkan konsep teras yang perlu anda fahami untuk menggunakan ESLint dengan menguntungkan.

Lebih lanjut mengenai konfigurasi rata

Dengan konsep konfigurasi rata baharu, keseluruhan konfigurasi projek adalah sebahagian daripada satu fail eslint.config.js(c|j|m). Sebelum ini, konfigurasi boleh disebarkan merentasi beberapa fail .eslintrc malah menjadi sebahagian daripada package.json, yang membawa kepada kerumitan dan kekeliruan.

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.

Generasi pertama linters

Dilancarkan sebagai salah satu alat linting pertama untuk JavaScript, JSLint dikenali sebagai nenek moyang linter JavaScript. Ia mempunyai pendapat tinggi dan tidak menyokong konfigurasi peraturan tersuai, menetapkan standard pengekodan yang ketat tanpa ruang untuk penyelewengan.

Muncul sebagai cabang JSLint, JSHint telah diperkenalkan untuk menawarkan pembangun lebih banyak pilihan konfigurasi. Walaupun begitu, ia tetap kurang fleksibel daripada ESLint, terutamanya dari segi penyesuaian peraturan dan sokongan pemalam, mengehadkan kebolehsesuaiannya kepada keperluan projek yang pelbagai. Keluaran terakhir bermula pada tahun 2022.

Pada mulanya alat linting yang digunakan untuk TypeScript, TSLint telah ditamatkan pada 2019 memihak kepada ESLint, yang memperluaskan keupayaannya untuk memasukkan TypeScript melalui pemalam. Penamatan TSLint menandakan perubahan ketara dalam komuniti TypeScript ke arah penyelesaian linting yang lebih bersatu.

Terserlah dalam kalangan rakan setara generasi pertamanya, ESLint telah menjadi alat dominan dalam ekosistem JavaScript sejak 2013. Kejayaannya dikaitkan dengan kebolehkonfigurasian yang meluas, ekosistem pemalam dan sokongan untuk peraturan tersuai, menjadikannya boleh disesuaikan dengan pelbagai gaya pengekodan dan keperluan projek.

Generasi kedua linters (Pasca-2020)

Lanskap alat linting JavaScript telah berkembang dengan ketara daripada alatan generasi pertama yang lebih berpendirian dan tegar kepada alatan generasi kedua yang memfokuskan prestasi dan lebih mudah diakses.

Sebagai sebahagian daripada barisan baharu ini, Biome muncul selepas wabak pada tahun 2020, tetapi di bawah nama Rome. Biome telah dicipta pada pertengahan 2023 sebagai percabangan Rom, yang merupakan projek aktif yang disokong oleh komuniti yang semakin berkembang. Biome memfokuskan pada skop yang lebih luas, termasuk pemformatan kod selain linting. Mengenai linting, sokongan bahasa belum lagi setanding dengan ESLint.

Dilancarkan pada 2021 dengan janji untuk meningkatkan aliran kerja pembangun, quick-lint-js meletakkan dirinya sebagai alat pelengkap kepada ESLint. Ia direka untuk "kelajuan masa nyata", menawarkan maklum balas pantas dalam editor kod anda tanpa kependaman. Matlamat lain alat ini ialah konfigurasi sifar, jadi ia adalah pendapat. Alat ini ditujukan kepada kumpulan sasaran tertentu.

Peserta yang agak baharu, RSLint memfokuskan pada menyediakan alat linting konfigurasi sifar. Ia dalam pembangunan awal dan tidak bersedia untuk pengeluaran. Keluaran terakhir adalah dari 2022, jadi tidak jelas sama ada pembangunan masih aktif.

Bermula pada Februari 2023, oxlint tidak bertujuan untuk menggantikan ESLint tetapi untuk melengkapkannya, terutamanya dalam senario di mana prestasi ESLint mungkin menjadi halangan. Ia menyokong JavaScript, TypeScript dan beberapa rangka kerja; cth., Vue.js.

Sebagai linter untuk masa jalan Deno, deno lint menyokong JavaScript dan TypeScript secara asli. Penyepaduannya dengan Deno membezakannya daripada pek yang lain, memenuhi keperluan khusus untuk projek yang menggunakan masa jalan ini.

Walaupun ESLint kekal sebagai asas kepada linting JavaScript, kemunculan alatan baharu mencerminkan pencarian berterusan komuniti untuk kecekapan, prestasi dan kebolehsuaian kepada keperluan projek tertentu. Hasil daripada impak generasi kedua ini masih berlaku, dengan banyak alat mencari niche mereka atau berfungsi sebagai pelengkap berharga kepada keupayaan komprehensif ESLint.

Jadual perbandingan: ESLint lwn. linters lain

Jadual berikut membandingkan ESLint dengan pesaing semasanya:

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

Saya mendapat tanggapan bahawa pasukan ESLint memandang serius beberapa kritikan dan menyelesaikannya dengan versi 9 — cth., pilihan lalai yang lebih wajar untuk mengatasi keperluan konfigurasi. Catatan blog yang diterbitkan baru-baru ini mengesahkan pandangan saya, kerana masih terdapat perubahan seni bina utama yang perlu dibuat pada teras ESLint, yang mungkin akan meningkatkan lagi prestasi.

Projek seperti Biome sememangnya salah satu sebab mengapa pasukan ESLint memutuskan untuk membuat penyesuaian yang kompleks ini. Beberapa alasan yang diberikan oleh pesaing mengapa penyelesaian mereka sendiri lebih baik daripada ESLint sudah lapuk.

Kesimpulan

Adakah anda perlu menggunakan ESLint sebagai alat linting pilihan anda? Saya mengesyorkan menggunakan ESLint dalam kebanyakan kes penggunaan, terutamanya dalam persekitaran komersial. ESLint diterima pakai dengan baik dan kemungkinan besar pembangun tahu cara menggunakannya kerana pengedaran yang meluas.

Malah projek pesaing yang bercita-cita tinggi masih belum dapat menampung semua kes penggunaan yang diperlukan oleh pembangun. Sebagai contoh, Biome tidak menyokong sepenuhnya CSS atau Vue.js mulai Julai 2024. Terdapat juga suara lain daripada komuniti yang menyokong penggunaan ESLint dengan Prettier sebagai gabungan terbaik untuk linting dan pemformatan.

Selalu ada kritikan mengenai kerumitan dan prestasi ESLint. Walau bagaimanapun, pengalaman projek konkrit dalam pasukan pembangunan, dokumentasinya yang sangat baik, dan perkakasan adalah hujah yang sangat baik yang memihak kepada ESLint.

Melainkan anda ingin merangkumi kes penggunaan yang sangat khusus, seperti maklum balas masa nyata dalam IDE (yang mungkin dengan quick-lint-js), ESLint merangkumi hampir semua kes penggunaan pembangunan yang berkaitan dengan set ciri yang kaya.


LogRocket: Nyahpepijat ralat JavaScript dengan lebih mudah dengan memahami konteks

Kod nyahpepijat sentiasa menjadi tugas yang membosankan. Tetapi semakin anda memahami kesilapan anda, semakin mudah untuk membetulkannya.

LogRocket membolehkan anda memahami ralat ini dengan cara baharu dan unik. Penyelesaian pemantauan bahagian hadapan kami menjejaki penglibatan pengguna dengan bahagian hadapan JavaScript anda untuk memberi anda keupayaan untuk melihat dengan tepat perkara yang dilakukan pengguna yang membawa kepada ralat.

ESLint adoption guide: Overview, examples, and alternatives

LogRocket merekodkan log konsol, masa muat halaman, surih tindanan, permintaan/tindak balas rangkaian perlahan dengan pengepala + badan, metadata penyemak imbas dan log tersuai. Memahami kesan kod JavaScript anda tidak akan menjadi lebih mudah!

Cuba secara percuma.

Atas ialah kandungan terperinci Panduan penggunaan ESLint: Gambaran keseluruhan, contoh dan alternatif. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn