[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,99 +2,185 @@
|
||||
id: wiki-2026-0508-eslint
|
||||
title: ESLint
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-BDDA30]
|
||||
aliases: [ESLint Flat Config, eslint.config.js]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
verification_status: applied
|
||||
tags: [javascript, typescript, lint, tooling, ast]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - ESLint"
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: JavaScript/TypeScript
|
||||
framework: ESLint 9.x
|
||||
---
|
||||
|
||||
# [[ESLint|ESLint]]
|
||||
# ESLint
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> ESLint는 자바스크립트 및 타입스크립트 코드에서 문법적 오류와 잠재적 버그를 식별하고 코딩 컨벤션을 강제하는 정적 분석 도구(Linter)입니다 [1, 2]. 소스 코드를 실행하지 않고 추상 구문 트리(AST)로 변환하여 사전에 정의된 논리 및 스타일 규칙을 적용함으로써 런타임 에러를 방지합니다 [3, 4]. 주로 코드 품질을 보장하고 팀 내 일관된 스타일을 유지하기 위해 사용되며, 코드 포매팅 도구인 [[Prettier|Prettier]]와 함께 모던 웹 개발 환경의 필수적인 도구로 활용됩니다 [1, 5].
|
||||
## 매 한 줄
|
||||
> **"매 JS/TS 의 pluggable AST-based linter"**. Nicholas Zakas 가 2013 시작 — 매 ESTree AST 의 traverse 후 매 rule 의 emit. 2024 v9 의 flat config (eslint.config.js) 의 default — 2026 매 typescript-eslint v8, Stylistic plugin, Biome 의 competition 안에서 매 still ecosystem default.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **정적 분석 및 코드 품질 관리**
|
||||
ESLint는 런타임 환경 이전에 소스 코드의 문제 패턴을 식별하는 정적 분석 도구입니다 [1, 6]. 사용되지 않는 변수, 글로벌 스코프 오염, 잘못된 API 사용 등 잠재적인 버그를 검출하고 코드 퀄리티 규칙을 강제하여 일관된 코드 작성을 돕습니다 [2, 7, 8]. 발견된 문제 중 특정 문법이나 스타일 위반은 `--fix` 옵션을 통해 자동으로 수정(Auto-fixing)할 수 있습니다 [9-11].
|
||||
## 매 핵심
|
||||
|
||||
* **설정 및 규칙 커스터마이징**
|
||||
ESLint의 규칙은 `off`(0), `warn`(1), `error`(2) 등 세 가지 수준으로 커스터마이징하여 적용할 수 있습니다 [12, 13]. 프로젝트별로 `.eslintrc` 파일이나 ESLint 9부터 도입된 Flat Config(예: `eslint.config.mjs`) 포맷을 통해 설정을 중앙화하고 관리할 수 있습니다 [14-16]. 주로 Airbnb나 Google 스타일 가이드처럼 널리 쓰이는 규칙을 확장(extends)하여 사용하며, TypeScript(`@typescript-eslint`), React(`eslint-plugin-react`) 등을 지원하는 다양한 서드파티 플러그인(plugins)을 장착할 수 있습니다 [17-19].
|
||||
### 매 architecture
|
||||
- **Parser**: source → ESTree AST (espree / `@typescript-eslint/parser` / hermes-parser).
|
||||
- **Rule**: AST visitor — `Program`, `CallExpression` 의 listen, `context.report()` 의 emit.
|
||||
- **Config (flat)**: array of objects — `files`, `languageOptions`, `plugins`, `rules`.
|
||||
- **Fixer**: rule 의 autofix function — `--fix` 의 apply.
|
||||
|
||||
* **Prettier와의 역할 분담 및 충돌 해결**
|
||||
ESLint는 코드 품질(버그 탐지)에 초점을 맞추는 반면, Prettier는 코드 포매팅(시각적 통일성)에 중점을 둡니다 [2, 5, 20]. ESLint에도 일부 포매팅 규칙이 포함되어 있어 두 도구를 함께 사용할 경우 충돌이 발생할 수 있습니다 [21, 22]. 이를 해결하기 위해 `[[eslint-config-prettier|eslint-config-prettier]]` 패키지를 사용하여 Prettier와 충돌하는 ESLint의 스타일 규칙을 비활성화(off)하는 방법이 가장 널리 권장됩니다 [21, 23-25].
|
||||
### 매 v9 flat config 의 핵심
|
||||
- **One file**: `eslint.config.js` (or `.mjs`/`.ts`) — 매 root cascade 의 X.
|
||||
- **Explicit imports**: 매 plugin/preset 의 `import` — magic string 의 X.
|
||||
- **Layer override**: array order 의 last-wins.
|
||||
- **`extends` 의 X**: 매 spread 의 use.
|
||||
|
||||
* **워크플로우 및 자동화 연동**
|
||||
코드 변경 사항이 Git 저장소에 반영되기 전, 나쁜 코드가 커밋되는 것을 방지하기 위해 자동화 파이프라인과 결합하여 사용됩니다 [26, 27]. 주로 `[[Husky|Husky]]`와 `lint-staged` 도구를 활용하여, Git의 `pre-commit` 훅(hook) 단계에서 변경된(staged) 파일에 대해서만 ESLint 검사 및 자동 수정을 실행하도록 구성합니다 [11, 28-30]. 대규모 모노레포([[Monorepo|Monorepo]]) 환경에서는 중복 구성을 피하기 위해 중앙집중식 ESLint 설정 패키지를 만들어 각 하위 패키지가 이를 공유하도록 구성하여 효율성을 극대화합니다 [15, 31, 32].
|
||||
### 매 응용
|
||||
1. CI gate (lint → typecheck → test).
|
||||
2. Editor inline diagnostic (VSCode ESLint extension).
|
||||
3. Pre-commit (lint-staged + husky).
|
||||
4. Codemod (autofixable rule 의 batch refactor).
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
## 💻 패턴
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[Prettier|Prettier]], Husky, lint-staged, [[정적 분석(Static Analysis)|정적 분석(Static Analysis]], [[AST(Abstract Syntax Tree)|AST(Abstract Syntax Tree]]
|
||||
- **Projects/Contexts:** [[모노레포(Monorepo) 기반 구성 중앙화|모노레포(Monorepo) 기반 구성 중앙화]], Git Hook을 이용한 CI/CD 자동화 파이프라인
|
||||
- **Contradictions/Notes:** 소스 [33]에서는 `[[eslint-plugin-prettier|eslint-plugin-prettier]]` 사용 시 에디터에 밑줄이 너무 많이 생기고 느려져 문서에서도 추천하지 않는다며 설정을 삭제했다고 언급하지만, 소스 [25]에서는 Prettier의 포매팅 이슈를 ESLint의 린터 오류로 띄워 통합적으로 관리할 수 있는 효과적인 방식이라고 설명하는 등 개발자 또는 조직 간의 `eslint-plugin-prettier` 활용에 대해 엇갈린 평가 및 설정 선호도 차이가 존재합니다.
|
||||
### Flat config — TS + React (2026)
|
||||
```js
|
||||
// eslint.config.js
|
||||
import js from '@eslint/js';
|
||||
import tseslint from 'typescript-eslint';
|
||||
import react from 'eslint-plugin-react';
|
||||
import reactHooks from 'eslint-plugin-react-hooks';
|
||||
import globals from 'globals';
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-18*
|
||||
|
||||
---
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
export default [
|
||||
js.configs.recommended,
|
||||
...tseslint.configs.recommendedTypeChecked,
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
languageOptions: {
|
||||
parserOptions: { project: './tsconfig.json' },
|
||||
globals: { ...globals.browser },
|
||||
},
|
||||
plugins: { react, 'react-hooks': reactHooks },
|
||||
rules: {
|
||||
...react.configs.recommended.rules,
|
||||
...reactHooks.configs.recommended.rules,
|
||||
'react/react-in-jsx-scope': 'off',
|
||||
'@typescript-eslint/no-floating-promises': 'error',
|
||||
},
|
||||
settings: { react: { version: 'detect' } },
|
||||
},
|
||||
{ ignores: ['dist/**', 'coverage/**'] },
|
||||
];
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Custom rule (no console.log in src)
|
||||
```js
|
||||
// rules/no-raw-console.js
|
||||
export default {
|
||||
meta: { type: 'problem', fixable: 'code', schema: [] },
|
||||
create(context) {
|
||||
return {
|
||||
'CallExpression[callee.object.name="console"][callee.property.name="log"]'(node) {
|
||||
context.report({
|
||||
node,
|
||||
message: 'Use logger.info instead of console.log',
|
||||
fix: (fixer) => fixer.replaceText(node.callee, 'logger.info'),
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Autofix rule — sort imports
|
||||
```js
|
||||
create(context) {
|
||||
return {
|
||||
Program(node) {
|
||||
const imports = node.body.filter(n => n.type === 'ImportDeclaration');
|
||||
const sorted = [...imports].sort((a, b) =>
|
||||
a.source.value.localeCompare(b.source.value));
|
||||
if (imports.some((n, i) => n !== sorted[i])) {
|
||||
context.report({
|
||||
node: imports[0],
|
||||
message: 'Imports must be sorted',
|
||||
fix: (fixer) => fixer.replaceTextRange(
|
||||
[imports[0].range[0], imports.at(-1).range[1]],
|
||||
sorted.map(n => context.sourceCode.getText(n)).join('\n')),
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### CLI + fix
|
||||
```bash
|
||||
npx eslint . --fix --max-warnings=0 --cache --cache-location=.eslintcache
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Pre-commit (lint-staged)
|
||||
```json
|
||||
{
|
||||
"lint-staged": {
|
||||
"*.{ts,tsx,js}": ["eslint --fix --max-warnings=0", "prettier --write"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### typescript-eslint 의 type-aware
|
||||
```js
|
||||
{
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
projectService: true, // 매 v8+ — auto tsconfig discovery
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'@typescript-eslint/no-misused-promises': 'error',
|
||||
'@typescript-eslint/await-thenable': 'error',
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| New project (2026) | Flat config + typescript-eslint v8 + projectService |
|
||||
| Monorepo | per-package config 의 spread + root ignore |
|
||||
| Speed-critical CI | Biome (formatter + lint) 의 partial replace 의 evaluate |
|
||||
| Style rule | ESLint Stylistic plugin (Prettier 와 separate) |
|
||||
| Editor experience | VSCode `eslint.useFlatConfig: true` |
|
||||
|
||||
**기본값**: flat config + typescript-eslint v8 + Stylistic + lint-staged.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[JavaScript Tooling]] · [[Static Analysis]]
|
||||
- 변형: [[Biome]] · [[Oxlint]] · [[deno lint]]
|
||||
- 응용: [[lint-staged]] · [[husky]]
|
||||
- Adjacent: [[Prettier]] · [[typescript-eslint]] · [[ESTree AST]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: rule lookup, flat config 의 migrate, custom rule scaffolding, AST selector 의 craft.
|
||||
**언제 X**: 매 specific plugin 의 latest API — version churn 매 빠름, docs 의 cross-check.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **`.eslintrc` 의 still 의 use (2026)**: v9 의 deprecate — flat config 의 migrate.
|
||||
- **Prettier rule 의 ESLint 안에서 enforce**: 매 conflict — separate run.
|
||||
- **`extends` chaining of unrelated configs**: 매 cascade 의 의 hard to debug — explicit imports 의 use.
|
||||
- **No `--cache`**: 매 large repo 의 slow — `.eslintcache` 의 enable.
|
||||
- **type-aware rule 의 large monorepo 의 enable**: parser overhead — 매 critical 의 만.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (eslint.org docs v9; typescript-eslint.io v8; ESLint blog 2024-04 flat config GA).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — flat config + typescript-eslint v8 정리 |
|
||||
|
||||
Reference in New Issue
Block a user