>  기사  >  웹 프론트엔드  >  ESLint 채택 가이드: 개요, 예시 및 대안

ESLint 채택 가이드: 개요, 예시 및 대안

WBOY
WBOY원래의
2024-08-08 22:30:52383검색

세바스티안 웨버 지음✏️

수년 동안 ESLint는 JavaScript 및 TypeScript 프로젝트 린팅의 사실상 표준이었습니다. 이 채택 가이드에서는 이것이 2024년에도 여전히 적용되는 이유를 설명합니다.

이 글은 작성 당시인 2024년 여름(v9.7)에 제공되었던 ESLint의 현재 버전을 다루고 있습니다. 따라서 v9의 개념과 기능만 설명하며 이는 이전 버전에 비해 몇 가지 주요 변경 사항을 가져옵니다.

플랫 구성 파일과 함께 최신 구성 버전 없이 이전 버전을 사용하려면 공식 마이그레이션 가이드를 참조하세요.

ESLint란 무엇입니까?

ESLint는 정적 코드 분석을 수행하기 위한 구성 및 확장 가능한 JavaScript 린터입니다. 소스 코드를 실행할 필요 없이 소스 코드의 문제를 추적하고 해결하는 데 도움이 됩니다. 문제는 잠재적인 런타임 버그, 잘못된 코딩 관행부터 코드 형식 문제까지 무엇이든 될 수 있습니다.

소프트웨어 품질 도구인 ESLint는 코드를 더욱 일관되고 강력하게 만드는 것을 목표로 합니다. 코드가 어떻게 보이거나 동작해야 하는지에 관해 소위 린트 규칙이라는 어설션을 사용하여 코드를 확인합니다. 예를 들어, no-use-before-define 규칙을 사용하면 ESLint가 선언되기 전에 함수 호출을 발견할 때 위반을 보고하도록 지시할 수 있습니다.

또한 각 규칙에 대해 위반 심각도를 경고 또는 오류로 지정할 수 있습니다. 따라서 CI/CD 파이프라인에서는 조사해야 할 더 큰 문제를 나타내는 보고된 오류에 대해 Linting 단계가 실패할 수 있습니다.

파서 및 플러그인의 도움을 받아 ESLint는 TypeScript나 JSX와 같은 JavaScript 구문 확장 또는 React나 Vue와 같은 JavaScript 프레임워크의 개념을 이해하고 린트하도록 구성할 수 있습니다.

ESLint가 왜 만들어졌나요?

ESLint라는 아이디어는 JSCS, JSLint, JSHint 등 당시 사용 가능한 Linting 도구가 부족했기 때문에 탄생했습니다. 이러한 도구는 규칙 세트와 구성 기능이 다소 엄격했기 때문에 특정 프로젝트 요구 사항에 따라 규칙을 조정하기가 어려웠습니다.

ESLint의 초기 버전부터 규칙은 ESLint의 백본을 구축했습니다. 마커와 오버레이를 사용하여 코드 편집기 내부의 문제가 있는 코드 위치에 직접 표시되는 위반을 수동으로 해결하는 방법에 대한 제안을 제공할 수 있습니다.

또한 규칙은 ESLint가 CLI 또는 코드 편집기의 위반을 자동으로 해결할 수 있도록 하는 수정 사항을 제공할 수 있습니다. 예를 들어 화살표 함수를 암시적 반환 변형으로 리팩토링합니다.

더 넓은 도구와 언어 지원을 통해 훨씬 더 나은 Linting 환경을 경험할 수 있을 뿐만 아니라 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 규칙 위반으로 인해 두 가지 오류를 보고했습니다. 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를 수익성 있게 사용하기 위해 이해해야 할 핵심 개념에 대해 설명하겠습니다.

플랫 구성에 대해 자세히 알아보기

새로운 플랫 구성 개념을 사용하면 전체 프로젝트 구성이 하나의 단일 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.

1세대 린터

최초의 JavaScript용 린팅 도구 중 하나로 출시된 JSLint는 JavaScript 린터의 조상으로 알려져 있습니다. 독선적이며 사용자 정의 규칙 구성을 지원하지 않으며 편차가 없는 엄격한 코딩 표준을 설정합니다.

JSLint의 포크로 등장한 JSHint는 개발자에게 더 많은 구성 옵션을 제공하기 위해 도입되었습니다. 그럼에도 불구하고 특히 규칙 사용자 정의 및 플러그인 지원 측면에서 ESLint보다 유연성이 떨어지므로 다양한 프로젝트 요구에 대한 적응성이 제한됩니다. 마지막 출시일은 2022년으로 거슬러 올라갑니다.

처음에는 TypeScript용 Linting 도구였던 TSLint는 플러그인을 통해 TypeScript를 포함하도록 기능을 확장한 ESLint를 위해 2019년부터 더 이상 사용되지 않습니다. TSLint의 지원 중단은 TypeScript 커뮤니티가 보다 통합된 린팅 솔루션을 향한 중요한 변화를 의미합니다.

1세대 동종 제품 중에서 두각을 나타내는 ESLint는 2013년부터 JavaScript 생태계에서 지배적인 도구가 되었습니다. ESLint의 성공은 광범위한 구성 가능성, 플러그인 생태계 및 사용자 정의 규칙 지원에 기인합니다. 코딩 스타일 및 프로젝트 요구사항

2세대 린터(2020년 이후)

JavaScript 린팅 도구 환경은 1세대의 보다 독선적이고 엄격한 도구에서 2세대의 성능 중심적이고 보다 접근하기 쉬운 도구로 크게 발전했습니다.

이러한 새로운 린터의 일환으로 Biome은 2020년 팬데믹 이후 등장했지만 이름은 Rome입니다. Biome은 2023년 중반에 로마의 포크로 만들어졌으며, 이는 성장하는 커뮤니티의 지원을 받는 활발한 프로젝트입니다. Biome은 Linting 외에도 코드 형식 지정을 포함하여 더 넓은 범위에 중점을 둡니다. Linting과 관련하여 언어 지원은 아직 ESLint와 동등하지 않습니다.

개발자 워크플로를 향상하겠다는 약속으로 2021년에 출시된 Quick-lint-js는 ESLint의 보완 도구로 자리매김했습니다. "실시간 속도"를 위해 설계되어 대기 시간 없이 코드 편집기 내에서 빠른 피드백을 제공합니다. 이 도구의 또 다른 목표는 제로 구성이므로 독선적입니다. 이 도구는 특정 대상 그룹을 대상으로 합니다.

비교적 신규 진입자인 RSLint는 구성이 필요 없는 Linting 도구를 제공하는 데 중점을 두고 있습니다. 아직 초기 개발 단계이고 생산 준비가 되어 있지 않습니다. 마지막 릴리스는 2022년이므로 아직 개발이 활발하게 진행되고 있는지는 불분명합니다.

2023년 2월부터 oxlint는 ESLint를 대체하기 위한 것이 아니라 ESLint의 성능에 병목 현상이 발생할 수 있는 시나리오에서 이를 보완하기 위한 것입니다. JavaScript, TypeScript 및 일부 프레임워크를 지원합니다. 예: Vue.js.

Deno 런타임용 린터인 deno lint는 기본적으로 JavaScript 및 TypeScript를 지원합니다. Deno와의 통합은 이 런타임을 활용하는 프로젝트에 특히 적합하다는 점에서 나머지 팩과 차별화됩니다.

ESLint는 JavaScript Linting의 초석으로 남아 있지만, 새로운 도구의 출현은 특정 프로젝트 요구 사항에 대한 효율성, 성능 및 적응성에 대한 커뮤니티의 지속적인 검색을 반영합니다. 이 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 팀이 이러한 복잡한 적응을 결정한 이유 중 하나입니다. 자신의 솔루션이 ESLint보다 나은 이유에 대해 경쟁업체가 제시한 일부 이유는 이미 구식입니다.

결론

선택한 린팅 도구로 ESLint를 고수해야 합니까? 대부분의 사용 사례, 특히 상업 환경에서는 ESLint를 사용하는 것이 좋습니다. ESLint는 잘 채택되었으며 광범위한 배포로 인해 개발자는 이를 사용하는 방법을 가장 잘 알고 있습니다.

야심 찬 경쟁 프로젝트조차도 개발자에게 필요한 모든 사용 사례를 아직 다룰 수는 없습니다. 예를 들어 Biome은 2024년 7월 현재 CSS 또는 Vue.js를 완전히 지원하지 않습니다. Linting 및 서식 지정을 위한 최상의 조합으로 ESLint와 Prettier의 사용을 옹호하는 커뮤니티의 다른 목소리도 있습니다.

ESLint의 복잡성과 성능에 대해서는 항상 비판이 있어 왔습니다. 그러나 개발 팀의 구체적인 프로젝트 경험, 매우 우수한 문서화 및 도구는 ESLint를 선호하는 매우 좋은 주장입니다.

IDE의 실시간 피드백(quick-lint-js로 가능)과 같이 매우 구체적인 사용 사례를 다루려는 경우를 제외하고 ESLint는 풍부한 기능 세트를 통해 거의 모든 관련 개발 사용 사례를 다룹니다.


LogRocket: 컨텍스트를 이해하여 JavaScript 오류를 더 쉽게 디버깅합니다.

코드 디버깅은 항상 지루한 작업입니다. 하지만 오류를 더 많이 이해할수록 오류를 수정하는 것이 더 쉬워집니다.

LogRocket을 사용하면 이러한 오류를 새롭고 독특한 방식으로 이해할 수 있습니다. 당사의 프런트엔드 모니터링 솔루션은 JavaScript 프런트엔드에 대한 사용자 참여를 추적하여 오류를 초래한 사용자의 행동을 정확하게 확인할 수 있는 기능을 제공합니다.

ESLint adoption guide: Overview, examples, and alternatives

LogRocket은 콘솔 로그, 페이지 로드 시간, 스택 추적, 헤더 + 본문이 포함된 느린 네트워크 요청/응답, 브라우저 메타데이터 및 사용자 정의 로그를 기록합니다. JavaScript 코드의 영향을 이해하는 것은 결코 쉬운 일이 아닙니다!

무료로 사용해 보세요.

위 내용은 ESLint 채택 가이드: 개요, 예시 및 대안의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.