[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,91 +2,221 @@
|
||||
id: wiki-2026-0508-eslint-plugin-development
|
||||
title: ESLint Plugin Development
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-ESPL-001]
|
||||
aliases: [ESLint Custom Rules, ESLint Plugin Authoring]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.96
|
||||
tags: [auto-reinforced, ESLint, plugin-development, static-Analysis, ast, JavaScript, dev-tooling, automation]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [eslint, plugin, ast, linting]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: JavaScript/TypeScript
|
||||
framework: ESLint 9
|
||||
---
|
||||
|
||||
# [[ESLint-Plugin-Development|ESLint-Plugin-Development]]
|
||||
# ESLint Plugin Development
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "우리 팀만의 보안 필터: 단순한 규칙 사용을 넘어, 프로젝트 고유의 설계 원칙이나 보안 취약점 정책을 감지하는 커스텀 로직을 플러그인 형태로 패키징하여 전사적으로 배포하고 코드 품질을 수평 전개하는 도구 제작기."
|
||||
## 매 한 줄
|
||||
> **"매 ESLint plugin은 AST visitor + RuleTester."**. ESLint 9 (2024-) Flat config 시대에는 plugin = `{rules, configs, processors}` object 의 export. 매 rule = `meta` (docs, fixable, schema) + `create(context)` returning visitor map (e.g., `CallExpression(node) { ... }`).
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
ESLint 플러그인 개발(ESLint-Plugin-Development)은 여러 ESLint 규칙(Rules)과 설정(Configs)을 하나의 모듈로 묶어 다른 프로젝트에서 재사용할 수 있게 만드는 과정입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **구조 요소**:
|
||||
* **Rules**: 실제 코드를 검사하는 로직 (AST 방문 주체). ([[Custom-ESLint-Rules|Custom-ESLint-Rules]]와 연결)
|
||||
* **Configs**: 권장되는 규칙 설정 세트 (예: `plugin:my-plugin/recommended`).
|
||||
* **Processors**: `.md`나 `.vue` 같은 비 JS 파일에서 JS 코드를 추출하는 전처리기.
|
||||
2. **왜 중요한가?**:
|
||||
* 대규모 조직에서 매번 각 프로젝트의 린트 설정을 복사-붙여넣기 할 필요 없이, 중앙 관리형 플러그인 정책을 통해 코드 표준 정책을 일회성으로 전파할 수 있기 때문임. ([[Efficiency|Efficiency]]와 연결)
|
||||
### 매 AST 기반
|
||||
- ESLint = ESTree spec (espree parser default; @typescript-eslint/parser for TS).
|
||||
- 매 rule visitor가 specific node type 방문 — `Identifier`, `CallExpression`, `JSXElement` 등.
|
||||
- `context.report({node, message, fix})` 으로 violation 보고.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 단순한 정규표현식 정책 검사에 가까웠으나, 현대 정책은 강력한 '타입 정보 정책(Type-aware linting)'을 활용하여 타입스크립트의 타입 관계 정책까지 검증하는 고수준 플러그인 정책으로 발전함(RL Update).
|
||||
- **정책 변화(RL Update)**: 이제는 단순 에러 감지 정책을 넘어, 복잡한 리팩토링 정책을 코드가 써진 순간 자동으로 수행(Fixer)해 주는 보좌진 역할을 수행함. ([[Quality-Control|Quality-Control]]와 연결)
|
||||
### 매 Plugin shape (Flat config)
|
||||
- ESLint 9+ deprecated `.eslintrc` 형식 — 매 `eslint.config.js` flat config.
|
||||
- Plugin export = `{meta, rules, configs, processors}` — meta에 `name/version` 명시.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Custom-ESLint-Rules|Custom-ESLint-Rules]], [[Efficiency|Efficiency]], [[Quality-Control|Quality-Control]], [[Technical-Architecture|Technical-Architecture]], Standard-Operating-Procedure, Automation
|
||||
- **Key Tools**: Yeoman generator-eslint, AST Explorer.
|
||||
---
|
||||
### 매 응용
|
||||
1. Internal style guide — 매 monorepo 의 component naming, import order.
|
||||
2. Framework rules — `eslint-plugin-react`, `eslint-plugin-vue` 처럼 framework-specific.
|
||||
3. Security lint — 매 dangerous API (eval, innerHTML) 금지.
|
||||
4. Migration codemod — 매 deprecated API 의 자동 fixer.
|
||||
|
||||
## 🤖 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
|
||||
### 1. Minimal rule skeleton
|
||||
```javascript
|
||||
// rules/no-foo.js
|
||||
export default {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: { description: 'disallow Foo identifier', recommended: true },
|
||||
fixable: 'code',
|
||||
schema: [],
|
||||
messages: { unexpected: "'{{name}}' is not allowed." },
|
||||
},
|
||||
create(context) {
|
||||
return {
|
||||
Identifier(node) {
|
||||
if (node.name === 'Foo') {
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'unexpected',
|
||||
data: { name: node.name },
|
||||
fix: (fixer) => fixer.replaceText(node, 'Bar'),
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### 2. Plugin entry (ESM, ESLint 9 flat)
|
||||
```javascript
|
||||
// index.js
|
||||
import noFoo from './rules/no-foo.js';
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
const plugin = {
|
||||
meta: { name: 'eslint-plugin-acme', version: '1.0.0' },
|
||||
rules: { 'no-foo': noFoo },
|
||||
};
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
plugin.configs = {
|
||||
recommended: {
|
||||
plugins: { acme: plugin },
|
||||
rules: { 'acme/no-foo': 'error' },
|
||||
},
|
||||
};
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
export default plugin;
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### 3. Consumer flat config
|
||||
```javascript
|
||||
// eslint.config.js
|
||||
import acme from 'eslint-plugin-acme';
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
export default [
|
||||
acme.configs.recommended,
|
||||
{ rules: { 'acme/no-foo': ['error'] } },
|
||||
];
|
||||
```
|
||||
|
||||
### 4. RuleTester (built-in test)
|
||||
```javascript
|
||||
import { RuleTester } from 'eslint';
|
||||
import rule from '../rules/no-foo.js';
|
||||
|
||||
const tester = new RuleTester({
|
||||
languageOptions: { ecmaVersion: 2024, sourceType: 'module' },
|
||||
});
|
||||
|
||||
tester.run('no-foo', rule, {
|
||||
valid: ['const Bar = 1;'],
|
||||
invalid: [{
|
||||
code: 'const Foo = 1;',
|
||||
errors: [{ messageId: 'unexpected' }],
|
||||
output: 'const Bar = 1;',
|
||||
}],
|
||||
});
|
||||
```
|
||||
|
||||
### 5. TypeScript rule with @typescript-eslint
|
||||
```typescript
|
||||
import { ESLintUtils } from '@typescript-eslint/utils';
|
||||
|
||||
const createRule = ESLintUtils.RuleCreator(
|
||||
(name) => `https://acme.dev/rules/${name}`,
|
||||
);
|
||||
|
||||
export default createRule({
|
||||
name: 'no-any',
|
||||
meta: {
|
||||
type: 'suggestion',
|
||||
docs: { description: 'disallow any' },
|
||||
schema: [],
|
||||
messages: { noAny: 'Avoid any; use unknown.' },
|
||||
},
|
||||
defaultOptions: [],
|
||||
create(context) {
|
||||
return {
|
||||
TSAnyKeyword(node) {
|
||||
context.report({ node, messageId: 'noAny' });
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### 6. Suggestions (non-auto fix)
|
||||
```javascript
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'considerRename',
|
||||
suggest: [{
|
||||
messageId: 'renameToBar',
|
||||
fix: (fixer) => fixer.replaceText(node, 'Bar'),
|
||||
}],
|
||||
});
|
||||
```
|
||||
|
||||
### 7. AST exploration (astexplorer.net)
|
||||
```javascript
|
||||
// Visitor pattern — leverage selector strings
|
||||
return {
|
||||
'CallExpression[callee.name="eval"]'(node) {
|
||||
context.report({ node, message: 'eval disallowed' });
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### 8. Scope / variable analysis
|
||||
```javascript
|
||||
create(context) {
|
||||
return {
|
||||
Identifier(node) {
|
||||
const scope = context.sourceCode.getScope(node);
|
||||
const variable = scope.references.find((r) => r.identifier === node);
|
||||
if (variable?.resolved?.defs[0]?.type === 'ImportBinding') {
|
||||
// imported identifier
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Codebase-specific 매 규칙 | Internal plugin (private npm). |
|
||||
| OSS 공유 | Publish `eslint-plugin-foo`. |
|
||||
| TS-only | `@typescript-eslint/utils` `RuleCreator`. |
|
||||
| 매 codemod 용 | jscodeshift / ts-morph (ESLint fix 보다 more powerful). |
|
||||
| 매 단순 ban API | `no-restricted-syntax` config — plugin 불필요. |
|
||||
|
||||
**기본값**: 매 ESLint 9 flat config + `@typescript-eslint/utils` RuleCreator.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[ESLint]] · [[AST]]
|
||||
- 변형: [[Stylelint Plugin]] · [[Biome]]
|
||||
- 응용: [[Code Review Automation]] · [[Monorepo Tooling]]
|
||||
- Adjacent: [[Prettier]] · [[TypeScript]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: AST visitor 작성, RuleTester case 생성, 매 selector string 의 작성.
|
||||
**언제 X**: 매 cross-file 분석 (ESLint = single-file) — 매 ts-morph / lsif 사용.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Regex on source**: 매 source string regex 의 X — 매 AST 사용.
|
||||
- **No tests**: 매 RuleTester 없는 rule 의 X — false positive 의 즉시 발생.
|
||||
- **Auto-fix without safety**: 매 fix가 매 semantics 변경 시 `suggest` 사용.
|
||||
- **`.eslintrc` in 2026**: 매 flat config 으로 migrate.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (ESLint 9 docs, eslint.org/docs/latest/extend).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — ESLint 9 flat config plugin authoring 패턴 |
|
||||
|
||||
Reference in New Issue
Block a user