ESLint 的规则
ESLint
的规则配置方法主要分两种,一种是直接设置规则的 error
warn
off
, 一种就是以数组的形式来设置规则的开启条件,以及需要附加的配置项,比如:
{
rules: {
// 代码结尾的分号
semi: 'off', // 值有 `error` 或 `2`、`warn` 或 `1`、`off` 或 `0`
// 字符串的单、双引号
quotes: ['error', 'single'] // 或是以数组的形式来进行配置规则的选项,选项还可以以对象的形式呈现
}
}
rules
中的每一个 key
即表示一条风格规则,我们可以思考一下如何去实现这些规则约束。
ESLint 的核心规则
先看一下简单的规则: no-with
:
module.exports = {
meta: {
// 包含规则的元数据
// 指示规则的类型,值为 "problem"、"suggestion" 或 "layout"
type: "suggestion",
docs: {
// 对 ESLint 核心规则来说是必需的
description: "disallow `with` statements", // 提供规则的简短描述在规则首页展示
// category (string) 指定规则在规则首页处于的分类
recommended: true, // 配置文件中的 "extends": "ESLint:recommended"属性是否启用该规则
url: "https://ESLint.org/docs/rules/no-with", // 指定可以访问完整文档的 url
},
// fixable // 如果没有 fixable 属性,即使规则实现了 fix 功能,ESLint 也不会进行修复。如果规则不是可修复的,就省略 fixable 属性。
schema: [], // 指定该选项 这样的 ESLint 可以避免无效的规则配置
// deprecated (boolean) 表明规则是已被弃用。如果规则尚未被弃用,你可以省略 deprecated 属性。
messages: {
unexpectedWith: "Unexpected use of 'with' statement.",
},
},
// create (function) 返回一个对象,其中包含了 ESLint 在遍历 js 代码的抽象语法树 AST (ESTree 定义的 AST) 时,用来访问节点的方法。
create(context) {
// 如果一个 key 是个节点类型或 selector,在 向下 遍历树时,ESLint 调用 visitor 函数
// 如果一个 key 是个节点类型或 selector,并带有 :exit,在 向上 遍历树时,ESLint 调用 visitor 函数
// 如果一个 key 是个事件名字,ESLint 为代码路径分析调用 handler 函数
// selector 类型可以到 estree 查找
return {
// 入参为节点node
WithStatement(node) {
context.report({ node, messageId: "unexpectedWith" });
},
};
},
};
规则由两部分组成: meta
create
;
meta
meta
对象是描述规则的元数据, 包括了规则的 类型
文档
是否可修复
等信息.
create
create
函数返回一个对象包含了 ESLint 在遍历 JavaScript 代码的抽象语法树(AST)
(ESTree 定义的 AST) 时, 用来访问节点的方法, 入参为该节点.
- 如果一个 key 是个节点类型或 selector,在 向下 遍历树时,ESLint 调用 visitor 函数
- 如果一个 key 是个节点类型或 selector,并带有
:exit
,在 向上 遍历树时,ESLint 调用 visitor 函数 - 如果一个 key 是个事件名字,ESLint 为 代码路径分析 调用 handler 函数
ESLint 命令的执行
在 package.json 里配置 bin
{
"name": "eslint",
"bin": {
"eslint": "bin/eslint.js"
},
"scripts": {
// ...
}
}
// 代码有删减
(async function main() {
// 如果在执行的时候带有 --init 参数则进行初始化 eslint 的配置
if (process.argv.includes("--init")) {
// `eslint --init` has been moved to `@eslint/create-config`
console.warn(
"You can also run this command directly using 'npm init @eslint/config'."
);
const spawn = require("cross-spawn");
spawn.sync("npm", ["init", "@eslint/config"], {
encoding: "utf8",
stdio: "inherit",
});
return;
}
// 没有附带 --init 参数则检查本地代码
process.exitCode = await require("../lib/cli").execute(
process.argv,
process.argv.includes("--stdin") ? await readStdin() : null
);
})();
ESLint 执行的调用栈
eslint
的主要代码执行逻辑流程如下:
- 解析命令行参数,校验参数正确与否及打印相关信息;
- 根据配置实例一个 engine 对象 CLIEngine 实例;
engine.executeOnFiles
读取源代码进行检查,返回报错信息和修复结果。
const cli = {
/**
* Executes the CLI based on an array of arguments that is passed in.
* @param {string|Array|Object} args The arguments to process.
* @param {string} [text] The text to lint (used for TTY).
* @returns {Promise<number>} The exit code for the operation.
*/
async execute(args, text) {
if (Array.isArray(args)) {
debug("CLI args: %o", args.slice(2));
}
/** @type {ParsedCLIOptions} */
let options;
try {
options = CLIOptions.parse(args);
} catch (error) {
log.error(error.message);
return 2;
}
const files = options._;
const useStdin = typeof text === "string";
if (options.help) {
log.info(CLIOptions.generateHelp());
return 0;
}
if (options.version) {
log.info(RuntimeInfo.version());
return 0;
}
if (options.envInfo) {
try {
log.info(RuntimeInfo.environment());
return 0;
} catch (err) {
log.error(err.message);
return 2;
}
}
if (options.printConfig) {
if (files.length) {
log.error(
"The --print-config option must be used with exactly one file name."
);
return 2;
}
if (useStdin) {
log.error(
"The --print-config option is not available for piped-in code."
);
return 2;
}
const engine = new ESLint(translateOptions(options));
const fileConfig = await engine.calculateConfigForFile(
options.printConfig
);
log.info(JSON.stringify(fileConfig, null, " "));
return 0;
}
debug(`Running on ${useStdin ? "text" : "files"}`);
if (options.fix && options.fixDryRun) {
log.error(
"The --fix option and the --fix-dry-run option cannot be used together."
);
return 2;
}
if (useStdin && options.fix) {
log.error(
"The --fix option is not available for piped-in code; use --fix-dry-run instead."
);
return 2;
}
if (options.fixType && !options.fix && !options.fixDryRun) {
log.error(
"The --fix-type option requires either --fix or --fix-dry-run."
);
return 2;
}
const engine = new ESLint(translateOptions(options));
let results;
if (useStdin) {
results = await engine.lintText(text, {
filePath: options.stdinFilename,
warnIgnored: true,
});
} else {
results = await engine.lintFiles(files);
}
if (options.fix) {
debug("Fix mode enabled - applying fixes");
await ESLint.outputFixes(results);
}
let resultsToPrint = results;
if (options.quiet) {
debug("Quiet mode enabled - filtering out warnings");
resultsToPrint = ESLint.getErrorResults(resultsToPrint);
}
if (
await printResults(
engine,
resultsToPrint,
options.format,
options.outputFile
)
) {
// Errors and warnings from the original unfiltered results should determine the exit code
const { errorCount, fatalErrorCount, warningCount } =
countErrors(results);
const tooManyWarnings =
options.maxWarnings >= 0 && warningCount > options.maxWarnings;
const shouldExitForFatalErrors =
options.exitOnFatalError && fatalErrorCount > 0;
if (!errorCount && tooManyWarnings) {
log.error(
"ESLint found too many warnings (maximum: %s).",
options.maxWarnings
);
}
if (shouldExitForFatalErrors) {
return 2;
}
return errorCount || tooManyWarnings ? 1 : 0;
}
return 2;
},
};
可以看到 eslint 实际上是在执行 engine.lintFiles(files)
方法:
async lintFiles(patterns) {
if (!isNonEmptyString(patterns) && !isArrayOfNonEmptyString(patterns)) {
throw new Error("'patterns' must be a non-empty string or an array of non-empty strings");
}
const { cliEngine } = privateMembersMap.get(this);
return processCLIEngineLintReport(
cliEngine,
cliEngine.executeOnFiles(patterns)
);
}
engine.lintFiles(files)
方法内部则是在执行 executeOnFiles(patterns)
方法来进行文件内容的校验.
executeOnFiles(patterns) 函数
executeOnFiles(patterns)
函数主要作用是对一组文件和目录名称执行当前配置. 看一下它做了什么:
executeOnFiles(patterns) {
const {
cacheFilePath,
fileEnumerator,
lastConfigArrays,
lintResultCache,
linter,
options: {
allowInlineConfig,
cache,
cwd,
fix,
reportUnusedDisableDirectives
}
} = internalSlotsMap.get(this);
const results = [];
const startTime = Date.now();
// Clear the last used config arrays.
lastConfigArrays.length = 0;
// Delete cache file; should this do here?
if (!cache) {
try {
fs.unlinkSync(cacheFilePath);
} catch (error) {
const errorCode = error && error.code;
// Ignore errors when no such file exists or file system is read only (and cache file does not exist)
if (errorCode !== "ENOENT" && !(errorCode === "EROFS" && !fs.existsSync(cacheFilePath))) {
throw error;
}
}
}
// Iterate source code files.
for (const { config, filePath, ignored } of fileEnumerator.iterateFiles(patterns)) {
if (ignored) {
results.push(createIgnoreResult(filePath, cwd));
continue;
}
/*
* Store used configs for:
* - this method uses to collect used deprecated rules.
* - `getRules()` method uses to collect all loaded rules.
* - `--fix-type` option uses to get the loaded rule's meta data.
*/
if (!lastConfigArrays.includes(config)) {
lastConfigArrays.push(config);
}
// Skip if there is cached result.
if (lintResultCache) {
const cachedResult =
lintResultCache.getCachedLintResults(filePath, config);
if (cachedResult) {
const hadMessages =
cachedResult.messages &&
cachedResult.messages.length > 0;
if (hadMessages && fix) {
debug(`Reprocessing cached file to allow autofix: ${filePath}`);
} else {
debug(`Skipping file since it hasn't changed: ${filePath}`);
results.push(cachedResult);
continue;
}
}
}
// Do lint.
const result = verifyText({
text: fs.readFileSync(filePath, "utf8"),
filePath,
config,
cwd,
fix,
allowInlineConfig,
reportUnusedDisableDirectives,
fileEnumerator,
linter
});
results.push(result);
/*
* Store the lint result in the LintResultCache.
* NOTE: The LintResultCache will remove the file source and any
* other properties that are difficult to serialize, and will
* hydrate those properties back in on future lint runs.
*/
if (lintResultCache) {
lintResultCache.setCachedLintResults(filePath, config, result);
}
}
// Persist the cache to disk.
if (lintResultCache) {
lintResultCache.reconcile();
}
debug(`Linting complete in: ${Date.now() - startTime}ms`);
let usedDeprecatedRules;
return {
results,
...calculateStatsPerRun(results),
// Initialize it lazily because CLI and `ESLint` API don't use it.
get usedDeprecatedRules() {
if (!usedDeprecatedRules) {
usedDeprecatedRules = Array.from(
iterateRuleDeprecationWarnings(lastConfigArrays)
);
}
return usedDeprecatedRules;
}
};
}
verifyText() 函数
verifyText()
则是调用了 linter.verifyAndFix()
函数.
verifyAndFix() 函数主要作用是对一组文件和目录名称执行当前配置
这个函数是核心函数,顾名思义 verify & fix 代码核心处理逻辑是通过一个 do while 循环控制;以下两个条件会打断循环
- 没有更多可以被 fix 的代码了
- 循环超过十次
- 其中 verify 函数对源代码文件进行代码检查,从规则维度返回检查结果数组
- applyFixes 函数拿到上一步的返回,去 fix 代码
- 如果设置了可以 fix,那么使用 fix 之后的结果 代替原本的 text
在 verify 过程中,会调用 parse 函数,把代码转换成 AST
// 默认的ast解析是espree
const espree = require("espree");
let parserName = DEFAULT_PARSER_NAME; // 'espree'
let parser = espree;
parse 函数会返回两种结果
{success: false, error: Problem}
解析 AST 成功{success: true, sourceCode: SourceCode}
解析 AST 失败
最终会调用 runRules() 函数
这个函数是代码检查和修复的核心方法,会对代码进行规则校验。
- 创建一个 eventEmitter 实例。是 eslint 自己实现的很简单的一个事件触发类 on 监听 emit 触发;
- 递归遍历 AST,深度优先搜索,把节点添加到 nodeQueue。一个 node 放入两次,类似于 A->B->C->…->C->B->A;
- 遍历 rules,调用 rule.create()(rules 中提到的 meta 和 create 函数) 拿到事件(selector)映射表,添加事件监听。
- 包装一个 ruleContext 对象,会通过参数,传给 rule.create(),其中包含 report() 函数,每个 rule 的 handler 都会执行这个函数,抛出问题;
- 调用 rule.create(ruleContext), 遍历其返回的对象,添加事件监听;(如果需要 lint 计时,则调用 process.hrtime()计时);
- 遍历 nodeQueue,触发当前节点事件的回调,调用 NodeEventGenerator 实例里面的函数,触发 emitter.emit()。
// 1. 创建一个 eventEmitter 实例。是eslint自己实现的很简单的一个事件触发类 on监听 emit触发
const emitter = createEmitter();
// 2. 递归遍历 AST,把节点添加到 nodeQueue。一个node放入两次 A->B->C->...->C->B->A
Traverser.traverse(sourceCode.ast, {
enter(node, parent) {
node.parent = parent;
nodeQueue.push({ isEntering: true, node });
},
leave(node) {
nodeQueue.push({ isEntering: false, node });
},
visitorKeys: sourceCode.visitorKeys,
});
// 3. 遍历 rules,调用 rule.create() 拿到事件(selector)映射表,添加事件监听。
// (这里的 configuredRules 是我们在 .eslintrc.json 设置的 rules)
Object.keys(configuredRules).forEach((ruleId) => {
const severity = ConfigOps.getRuleSeverity(configuredRules[ruleId]);
// 通过ruleId拿到每个规则对应的一个对象,里面有两部分 meta & create 见 【编写rule】
const rule = ruleMapper(ruleId);
// ....
const messageIds = rule.meta && rule.meta.messages;
let reportTranslator = null;
// 这个对象比较重要,会传给 每个规则里的 rule.create函数
const ruleContext = Object.freeze(
Object.assign(Object.create(sharedTraversalContext), {
id: ruleId,
options: getRuleOptions(configuredRules[ruleId]),
// 每个rule的 handler 都会执行这个函数,抛出问题
report(...args) {
if (reportTranslator === null) {
reportTranslator = createReportTranslator({
ruleId,
severity,
sourceCode,
messageIds,
disableFixes,
});
}
const problem = reportTranslator(...args);
// 省略一堆错误校验
// ....
// 省略一堆错误校验
// lint的结果
lintingProblems.push(problem);
},
})
);
// 包装了一下,其实就是 执行 rule.create(ruleContext);
// rule.create(ruleContext) 会返回一个对象,key就是事件名称
const ruleListeners = createRuleListeners(rule, ruleContext);
/**
* 在错误信息中加入ruleId
* @param {Function} ruleListener 监听到每个node,然后对应的方法rule.create(ruleContext)返回的对象中对应key的value
* @returns {Function} ruleListener wrapped in error handler
*/
function addRuleErrorHandler(ruleListener) {
return function ruleErrorHandler(...listenerArgs) {
try {
return ruleListener(...listenerArgs);
} catch (e) {
e.ruleId = ruleId;
throw e;
}
};
}
// 遍历 rule.create(ruleContext) 返回的对象,添加事件监听
Object.keys(ruleListeners).forEach((selector) => {
const ruleListener = timing.enabled
? timing.time(ruleId, ruleListeners[selector]) // 调用process.hrtime()计时
: ruleListeners[selector];
// 对每一个 selector 进行监听,添加 callback
emitter.on(selector, addRuleErrorHandler(ruleListener));
});
});
// 只有顶层node类型是Program才进行代码路径分析
const eventGenerator =
nodeQueue[0].node.type === "Program"
? new CodePathAnalyzer(
new NodeEventGenerator(emitter, {
visitorKeys: sourceCode.visitorKeys,
fallback: Traverser.getKeys,
})
)
: new NodeEventGenerator(emitter, {
visitorKeys: sourceCode.visitorKeys,
fallback: Traverser.getKeys,
});
// 4. 遍历 nodeQueue,触发当前节点事件的回调。
// 这个 nodeQueue 是前面push进所有的node,分为 入口 和 离开
nodeQueue.forEach((traversalInfo) => {
currentNode = traversalInfo.node;
try {
if (traversalInfo.isEntering) {
// 调用 NodeEventGenerator 实例里面的函数
// 在这里触发 emitter.emit()
eventGenerator.enterNode(currentNode);
} else {
eventGenerator.leaveNode(currentNode);
}
} catch (err) {
err.currentNode = currentNode;
throw err;
}
});
// lint的结果
return lintingProblems;
执行节点匹配 NodeEventGenerator
在该类里面,会根据前面 nodeQueque 分别调用 进入节点和离开节点,来区分不同的调用时机。
// 进入节点 把这个node的父节点push进去
enterNode(node) {
if (node.parent) {
this.currentAncestry.unshift(node.parent);
}
this.applySelectors(node, false);
}
// 离开节点
leaveNode(node) {
this.applySelectors(node, true);
this.currentAncestry.shift();
}
// 进入还是离开 都执行的这个函数
// 调用这个函数,如果节点匹配,那么就触发事件
applySelector(node, selector) {
if (esquery.matches(node, selector.parsedSelector, this.currentAncestry, this.esqueryOptions)) {
// 触发事件,执行 handler
this.emitter.emit(selector.rawSelector, node);
}
}
总体运行机制
概括来说就是,ESLint 会遍历前面说到的 AST,然后在遍历到「不同的节点」或者「特定的时机」的时候,触发相应的处理函数,然后在函数中,可以抛出错误,给出提示。