Processor
ESLint 处理器让ESLint可以从其他类型的文件中提取 JavaScript 代码,然后再让ESLint 对 JavaScript 代码进行检查。当然,除了以上,也可以使用处理器在使用 ESLint 解析 JavaScript 代码之前对其进行一些其他的操作。
eslint-plugin-markdown 包含一个自定义处理器,可以在 Markdown 代码块内对 JavaScript 代码进行检查。
eslint-plugin-markdown
PreProcess
主要功能就是提取markdown文件中代码块中的内容。
Parse
- 确定parser
eslint-plugin-markdown使用mdast-util-from-markdown parser,它可以将markdown转化为AST
- 执行parse生成AST:
遍历AST
将AST Node类型为"code"的节点添加到筛选结果中
返回结果
处理遍历生成的结果,生成ESLint preprocess API所规定的格式。即:
module.exports = {
processors: {
".markdown": {
preprocess: function(text, filename) {
return [ // return an array of code blocks to lint
{ text: code1, filename: "0.js" },
{ text: code2, filename: "1.js" },
];
}
}
}
};
举个例子,以下是Markdown源代码被Preprocess后的结果
- Markdown源代码
## 这是一个markdown文件
```javascript
let aa = 2;
```
```js
let x = 999;
```
- Preprocess生成的结果
PostProcess
主要功能是对Lint检查的结果做格式化处理(拍平)以及信息矫正。PreProcess处理后,得到JavaScript代码,ESLint拿到JavaScript代码再进行处理,从而得到Report与Linting Problems。不过,生成的Report与Linting Problems的信息还不能直接指出Markdown文件中出问题的位置,因为ESLint是基于PreProcess处理后的结果来生成的。简单来说,ESLint基于提取出的JavaScript代码生成出来的Report与Linting Problem的信息并不能与Markdown源文件匹配,相关信息会有一定的位置偏差,所以需要做位置偏移矫正。
那么adjustBlock是如何矫正的呢?
举个例子,以下为Markdown源文件内容
## 这是一个markdown文件
```javascript
let aa = 2;
```
```js
let x = 999;
```
展示效果如下
对行、列做偏移调整,偏移调整的值就是当前代码块Markdown上的偏移量。
得到结果,可以看到加上了JavaScirpt代码块前面Markdown的行数,这样位置就对上了。
调整前的Linting Problems
let x = 999;
{
column: 5,
endColumn: 6,
line: 1,
endline: 1
}
调整后的Linting Problems
## 这是一个markdown文件
```javascript
let aa = 2;
```
```js
let x = 999;
```
{
column: 5,
endColumn: 6,
line: 10,
endline: 10
}
总结
Processor的主要作用是从其他类型的文件中提取 JavaScript 代码,从而让ESLint有处理其他类型文件的能力。eslint-plugin-markdown插件就是从Markdown文件中提取JavaScript代码,主要原理也是解析Markdown内容生成AST,从AST中提取JavaScript内容,再对生成的Linting Problems做偏移矫正,最后得到Markdown内容中JavaScript代码的Lint Report与Lint Problems。