ESLint 文档站代码块正误标记:`::: correct` / `::: incorrect` 容器组件全解析
ESLint 文档站代码块正误标记:::: correct / ::: incorrect 容器组件全解析
ESLint 官方文档站(本仓库 docs/ 目录,基于 Eleventy 构建)在几乎所有规则页中都会用"正确用法 / 错误用法"两种代码块直观对比规则行为。docs/src/library/code-blocks.md 正是这一组件库的规范文档,它定义了如何用 ::: correct 与 ::: incorrect 容器标记代码块,并在渲染时自动附加正确(✔)与错误(✖)图标。本文以该文档为主体,结合仓库中的 docs/tools/ 构建插件源码,说明完整语法、真实示例、可选的 languageOptions 扩展参数,以及"错误代码被真实 Lint 并高亮"的底层实现原理,帮助你掌握在 ESLint 文档中编写正误对照代码块的全部细节。
一、组件是什么:规则文档中的"正误对照"惯例
浏览任意 ESLint 规则页(如 docs/src/rules/accessor-pairs.md、docs/src/rules/array-bracket-spacing.md),你都会看到大量成对出现的代码示例:左侧或上方是"错误的写法",右侧或下方是"正确的写法"。这正是本组件提供的核心能力——给代码块附加正确 / 错误语义图标,让读者一眼识别示例的合规性。
该组件的规范文档是 docs/src/library/code-blocks.md,它属于文档站的组件库(docs/src/library/library.json 将该组件页挂载到 /component-library/code-blocks.html),与 docs/src/library/rule-example.md(规则示例组件)、docs/src/library/code-tabs.md(代码标签页组件)共同构成文档站代码展示的基础设施。
二、基本用法:用容器标记代码块
在文档的 Markdown 源码中,将代码块包裹在标注为 correct 或 incorrect 的容器内,即可声明其语义:
::: correct—— 标记为正确用法,渲染时显示正确图标;::: incorrect—— 标记为错误用法,渲染时显示错误图标。
::: correct
```js
function() {
const another = [];
}
:::
::: incorrect
function() {
const another = [];
}
:::
关键约束(务必遵守,否则渲染异常):
- **容器标记行与代码块之间必须保留空行**。容器起始标记 `::: correct` 之后、代码块之前各留一个空行,代码块之后、结束标记 `::: ` 之前同样留一个空行。这是 `markdown-it-container` 插件正常识别容器边界的必要条件。
- 容器必须成对出现:以 `::: 标签` 开始,以 `:::` 结束。
- 代码块的语言标识(如 `js`)按需填写,语法高亮由 Prism 负责(见下文第五节)。
## 三、完整示例:ESLint Node.js API 的正误对照
`docs/src/library/code-blocks.md` 给出了一个真实可运行的对照示例——使用 ESLint 的 Node.js API 修复代码并输出结果:
**正确用法**(完整、可运行):
```js
const { ESLint } = require("eslint");
(async function main() {
// 1. Create an instance with the `fix` option.
const eslint = new ESLint({ fix: true });
// 2. Lint files. This doesn't modify target files.
const results = await eslint.lintFiles(["lib/**/*.js"]);
// 3. Modify the files with the fixed code.
await ESLint.outputFixes(results);
// 4. Format the results.
const formatter = await eslint.loadFormatter("stylish");
const resultText = formatter.format(results);
// 5. Output it.
console.log(resultText);
})().catch(error => {
process.exitCode = 1;
console.error(error);
});
错误用法(同一段代码,但语义被标记为错误):
const { ESLint } = require("eslint");
(async function main() {
// 1. Create an instance with the `fix` option.
const eslint = new ESLint({ fix: true });
// 2. Lint files. This doesn't modify target files.
const results = await eslint.lintFiles(["lib/**/*.js"]);
// 3. Modify the files with the fixed code.
await ESLint.outputFixes(results);
// 4. Format the results.
const formatter = await eslint.loadFormatter("stylish");
const resultText = formatter.format(results);
// 5. Output it.
console.log(resultText);
})().catch(error => {
process.exitCode = 1;
console.error(error);
});
这两段代码在 docs/src/library/code-blocks.md 中分别被 ::: correct 和 ::: incorrect 包裹。示例演示了 ESLint 程序化接口的标准流程:通过 ESLint({ fix: true }) 创建实例 → lintFiles() 检查文件(不直接修改)→ ESLint.outputFixes() 将修复写回文件 → loadFormatter("stylish") 加载格式化器 → 输出报告;错误通过 process.exitCode = 1 传播。对应实现可参见 lib/eslint/eslint.js 中的 lintFiles、outputFixes、loadFormatter 等方法。
四、进阶用法:在标签后追加 languageOptions
基础语法之外,仓库的容器解析插件还支持在 correct / incorrect 标签后以 JSON 追加语言选项,语法为:
::: incorrect { "sourceType": "script" }
```js
var foo = 1;
:::
这一能力由 [docs/tools/markdown-it-rule-example.js](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/tools/markdown-it-rule-example.js?utm_source=gitcode_repo_files) 的解析逻辑支撑:其 `render` 函数通过正则 `/^\s*(?<type>\S+)(?:\s+(?<languageOptionsJSON>\S(?:.*\S)?))?/u` 提取标签后的 JSON 字符串,并调用 `JSON.parse` 得到 `languageOptions` 对象,最终以参数形式传递给上层渲染回调。
该语法在规则文档中被大量使用,常见取值包括:
| 规则文档 | 标签写法 | 用途 |
| --- | --- | --- |
| [docs/src/rules/global-require.md](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/src/rules/global-require.md?utm_source=gitcode_repo_files#L32-L75) | `::: incorrect { "sourceType": "script" }` | 声明代码为 Script 模式(非模块) |
| [docs/src/rules/consistent-this.md](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/src/rules/consistent-this.md?utm_source=gitcode_repo_files#L72) | `::: incorrect { "sourceType": "script" }` | 同上 |
| [docs/src/rules/jsx-quotes.md](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/src/rules/jsx-quotes.md?utm_source=gitcode_repo_files#L37-L76) | `::: incorrect { "parserOptions": { "ecmaFeatures": { "jsx": true } } }` | 开启 JSX 解析能力 |
| [docs/src/rules/lines-around-directive.md](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/src/rules/lines-around-directive.md?utm_source=gitcode_repo_files#L59) | `::: correct { "sourceType": "script" }` | 同上 |
这些 `languageOptions` 不仅影响代码展示,还会被真实传入 ESLint Linter 用于校验(见下节)。从源码类型定义([docs/tools/markdown-it-rule-example.js](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/tools/markdown-it-rule-example.js?utm_source=gitcode_repo_files#L5) 中的 `JSLanguageOptions`)看,其取值与 ESLint 平级配置(flat config)中的 `languageOptions` 一致,即 `sourceType`、`parserOptions`、`globals` 等字段。
## 五、底层原理:`correct` / `incorrect` 容器如何被渲染
### 1. markdown-it-container 插件:识别与解析
`docs/tools/markdown-it-rule-example.js` 导出的 `markdownItRuleExample({ open, close })` 工厂函数,专门生成 `markdown-it-container` 的配置对象,自动化处理以下工作:
- **严格匹配标签**:`validate` 回调使用正则 `/^\s*(?:in)?correct(?!\S)/u`,保证只有 `correct` 或 `incorrect` 开头的容器块才会命中该插件,避免误拦截其他容器语法(如 `::: tip` 提示块);
- **解析可选 JSON**:从标签行提取并解析 `languageOptions` JSON(见第四节);
- **预处理代码**:将容器内代码块的内容交给 `docsExampleCodeToParsableCode` 处理(见下文第六节);
- **回调扩展**:开放 `open` 回调(必填)与 `close` 回调(可选),渲染时若回调返回字符串则追加到输出中。这就是"正确/错误图标"的挂载点——例如将代码注入到 Playground 供读者在线试跑。
`validate` 与 `render` 的具体实现可参见 [docs/tools/markdown-it-rule-example.js](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/tools/markdown-it-rule-example.js?utm_source=gitcode_repo_files#L60-L99)。
### 2. Prism ESLint 标记钩子:对"错误示例"真实执行 Lint 并高亮
`docs/tools/prism-eslint-hook.js` 实现了一个更强大的能力:**当页面渲染到 `::: incorrect` 容器中的代码时,会真实运行 ESLint 对该代码进行校验,并把报错范围用红色标记渲染到代码块中**。其工作链路如下:
1. 通过 `addContentMustBeMarked(content, options)` 记录当前需要标记的代码及其 `languageOptions`(`::: correct` / `::: incorrect` 容器的 open 回调会调用它);
2. 注册 `Prism.hooks.add("after-tokenize", ...)` 钩子:当被标记的代码完成 Prism 语法分词后,创建 `new Linter({ configType: "flat" })`(见 [lib/linter/linter.js](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/lib/linter/linter.js?utm_source=gitcode_repo_files) 的 `Linter` 类),用 `linter.verify(code, config)` 执行校验;
3. 将 Lint 消息(`message.line` / `message.column` / `endLine` / `endColumn`)转换为字符区间 `range`,并调用 `convertMarked` / `splitToken` 把 Prism token 流在报错区间切分成带 `eslint-marked` 类的 token;
4. 注册 `Prism.hooks.add("wrap", ...)` 钩子:在输出阶段为被标记的 token 附加 `title` 属性(即 Lint 报错文本,鼠标悬停可见);若错误落在空字符串、BOM(`\ufeff`)或换行符上,则追加 `eslint-marked-on-zero-width` / `eslint-marked-on-line-feed` 类,保证零宽与换行位置的错误也能被可见地画出下划线。
值得注意的是,该钩子仅在英文站点启用:代码中通过 `require("../../lib/api").Linter` 与 `require("../../lib/shared/ast-utils")` 是否可用来判断环境([docs/tools/prism-eslint-hook.js](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/tools/prism-eslint-hook.js?utm_source=gitcode_repo_files#L21-L27)),在翻译站点等没有这些模块的环境下会自动退化为空操作(noop),避免构建失败。
### 3. 从"示例代码"到"可解析代码"的预处理
无论是插件解析还是 Lint 校验,代码都先经过 `docs/tools/code-block-utils.js` 中导出的 `docsExampleCodeToParsableCode(code)` 处理([docs/tools/code-block-utils.js](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/tools/code-block-utils.js?utm_source=gitcode_repo_files#L14-L27)),它完成三类转换:
1. **移除末尾换行**:Markdown 代码块内容末尾总是多一个换行符,先将其去掉;
2. **保留 CRLF**:将 `\r\n` 序列后紧跟的 `\n` 替换为 `\r\n`,使 Windows 风格的换行在示例中得以保留;
3. **移除展示性 `⏎` 符号**:文档中用于展示"行尾有换行"的 `⏎` 字符会被删除——这是 eslint/eslint#17627 引入的约定,用于在规则文档中直观展示行尾符,但送入 Linter 前必须还原。
源码注释特别提醒:替换必须保证**不改变行列位置**,否则会导致错误标记定位偏移。
## 六、使用规范与注意事项小结
综合 `docs/src/library/code-blocks.md` 文档与插件源码,编写正误代码块时请遵守以下规范:
1. **成对使用**:需要对照时分别写 `::: correct` 与 `::: incorrect` 两个容器;
2. **保留空行**:容器标记与代码块之间、代码块与结束标记之间必须各留一个空行,否则渲染不可靠;
3. **语言标识**:代码块第一行写上语言(如 `js`),以便 Prism 高亮与 Lint 校验;
4. **善用 `languageOptions`**:当示例依赖特定解析模式(如 `sourceType: "script"`、JSX)时,以 JSON 形式追加在标签后,保证 Lint 校验与代码展示语境一致;
5. **展示行尾时使用 `⏎`**:需要展示行尾换行时在行尾书写 `⏎`,构建期会被自动剥离,不影响校验结果;
6. **错误示例会被真实 Lint**:`::: incorrect` 中的代码在英文站点构建时会被真实校验并高亮报错区间,因此示例代码必须确实能触发期望的报错,且要保证语法可解析——若代码有致命语法错误,钩子会直接跳过标记(`if (lintMessages.some(m => m.fatal)) return;`)。
## 七、相关资源速览
- 组件规范文档:[docs/src/library/code-blocks.md](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/src/library/code-blocks.md?utm_source=gitcode_repo_files)
- 组件挂载配置:[docs/src/library/library.json](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/src/library/library.json?utm_source=gitcode_repo_files)
- 容器解析插件:[docs/tools/markdown-it-rule-example.js](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/tools/markdown-it-rule-example.js?utm_source=gitcode_repo_files)
- Lint 标记与高亮钩子:[docs/tools/prism-eslint-hook.js](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/tools/prism-eslint-hook.js?utm_source=gitcode_repo_files)
- 代码预处理工具:[docs/tools/code-block-utils.js](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/tools/code-block-utils.js?utm_source=gitcode_repo_files)
- 语法高亮前置钩子:[docs/tools/md-syntax-highlighter.js](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/src/_plugins/md-syntax-highlighter.js?utm_source=gitcode_repo_files)
- 实际使用范例:规则文档目录 [docs/src/rules/](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/src/rules/?utm_source=gitcode_repo_files) 中几乎所有规则页均使用了 `::: correct` / `::: incorrect` 语法,可参考 [docs/src/rules/accessor-pairs.md](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/src/rules/accessor-pairs.md?utm_source=gitcode_repo_files)、[docs/src/rules/jsx-quotes.md](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/src/rules/jsx-quotes.md?utm_source=gitcode_repo_files)、[docs/src/rules/global-require.md](https://gitcode.com/GitHub_Trending/es/eslint/blob/87e0a082438264ad90b87fd74165ab4fd90f63ef/docs/src/rules/global-require.md?utm_source=gitcode_repo_files)
掌握以上语法与实现机制后,你既可以仿照本仓库规则文档的写法,在自己基于 Eleventy + markdown-it 的文档站中复刻"正确 / 错误代码对照 + 真实 Lint 高亮"的展示效果,也可以直接复用 `docs/tools/` 下的三个构建工具为现有文档站赋能。