93 lines
2.5 KiB
Markdown
93 lines
2.5 KiB
Markdown
# Step 04 — Phase 2.3: Stylelint 适配器
|
|
|
|
**依赖**: Step 02
|
|
**参考设计**: §3.3
|
|
|
|
## 目标
|
|
|
|
实现 CSS 的 Stylelint 适配器,用 stylelint npm 包直接检查代码。
|
|
|
|
## 前置准备
|
|
|
|
```bash
|
|
npm install --save stylelint@^17.14.0
|
|
```
|
|
|
|
## 新建文件
|
|
|
|
| # | 文件 | 说明 |
|
|
|---|------|------|
|
|
| 1 | `src/adapters/stylelint.ts` | `StylelintAdapter` |
|
|
|
|
---
|
|
|
|
## `src/adapters/stylelint.ts`
|
|
|
|
```typescript
|
|
import * as vscode from 'vscode';
|
|
import { LinterAdapter, LinterDiagnostic, AdapterResult } from '../types';
|
|
|
|
export class StylelintAdapter implements LinterAdapter {
|
|
id = 'stylelint';
|
|
supportedLanguages = ['css'];
|
|
|
|
async check(document: vscode.TextDocument, _workingDir: string): Promise<AdapterResult> {
|
|
try {
|
|
const code = document.getText();
|
|
const stylelint = await import('stylelint');
|
|
const result = await stylelint.default.lint({
|
|
code,
|
|
codeFilename: document.uri.fsPath,
|
|
config: { rules: {} },
|
|
});
|
|
|
|
const diagnostics: LinterDiagnostic[] = [];
|
|
for (const warning of result.results[0]?.warnings ?? []) {
|
|
const line = Math.max(0, (warning.line ?? 1) - 1);
|
|
const column = Math.max(0, (warning.column ?? 1) - 1);
|
|
const range = new vscode.Range(line, column, line, column + 1);
|
|
diagnostics.push({
|
|
severity: warning.severity === 'error' ? 'error' : 'warning',
|
|
ruleId: `stylelint:${warning.rule}`,
|
|
message: warning.text,
|
|
range,
|
|
});
|
|
}
|
|
return { diagnostics, status: 'ok' };
|
|
} catch (err) {
|
|
const message = err instanceof Error ? err.message : String(err);
|
|
if (message.includes('Cannot find module')) {
|
|
return { diagnostics: [], status: 'tool-unavailable', errorMessage: 'Stylelint 未安装,请执行 npm install stylelint' };
|
|
}
|
|
return { diagnostics: [], status: 'execution-failed', errorMessage: message };
|
|
}
|
|
}
|
|
|
|
isAvailable(): boolean {
|
|
try {
|
|
require.resolve('stylelint');
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## 关键逻辑
|
|
|
|
- `check()`: 使用 `stylelint.lint({ code, codeFilename })` 直接检查代码文本,支持虚拟文档
|
|
- ruleId 加前缀 `stylelint:`,如 `stylelint:color-no-invalid-hex`
|
|
- `isAvailable()`: 通过 `require.resolve` 检测 stylelint 是否已安装
|
|
- 错误处理:模块未找到 → `tool-unavailable`,其他错误 → `execution-failed`
|
|
|
|
---
|
|
|
|
## 验收
|
|
|
|
- [ ] 文件创建完成
|
|
- [ ] `npm run compile` 通过
|
|
- [ ] `npm run lint` 通过
|