背景
自定义 eslint 规则模板,官方提供的 JS 模板缺少类型以及一些提高生产力的工具。
本文模板参考 github.com/antfu/eslin… 和 github.com/sindresorhu…
模板
JS:
const { ESLintUtils } = require('@typescript-eslint/utils');
const { isComment } = require('../../utils/lodash');
const {
MSG_ID_COMPLEX_REGEXP_SHOULD_BE_COMMENTED: messageId,
} = require('../../utils/constants');
// /\d{1,2}/.length = 9
const DEFAULT_MIN_LENGTH = 9;
/** @type {import('typings/eslint').JSONSchema.JSONSchema4}*/
const OPTIONS_SCHEMA = {
type: 'object',
properties: {
minLength: {
type: 'integer',
description: `判断为复杂正则表达式的长度,默认 ${DEFAULT_MIN_LENGTH}`
}
},
additionalProperties: false
};
const msg = '[CodeStyle] 复杂正则表达式缺少注释';
const url = 'https://xxx';
module.exports = ESLintUtils.RuleCreator(_name => url)({
name: messageId,
meta: {
type: 'suggestion',
docs: {
description: msg,
recommended: 'warn',
},
schema: [
OPTIONS_SCHEMA,
],
messages: {
[messageId]: msg,
}
},
defaultOptions: [{ minLength: DEFAULT_MIN_LENGTH }],
create: function (context, options) {
const sourceCode = context.getSourceCode();
return {
Literal(node) {
const value = node.value;
const { minLength } = options[0];
const startLine = sourceCode.lines[node.loc.start.line - 2];
// console.log('startLine:', startLine);
const commented = isComment(startLine);
// console.log('comment:', {comment, comments, commented});
if (value instanceof RegExp && String(value).length > minLength && !commented) {
context.report({
node,
messageId,
});
}
},
}
}
});