1.问题:javascript standard style如何自定义plugin。
2.自定义plugin: eslint-plugin-test 代码:
const legalExpression = [];
console.log('test')
module.exports = {
rules: {
'caught-dangerous-call': {
create: function(context) {console.log('CallExpression');
return {
CallExpression: function(node) {
if (access(node, 'callee.property.name') === 'startsWith') {
if (legalExpression.indexOf('startsWith') < 0) {
context.report({
node: node,
message: 'startsWith is dangerous'
});
}
}
}
}
}
},
'caught-override': {
create: function(context) {console.log('AssignmentExpression');
return {
AssignmentExpression: function(node) {
let left = access(node, 'left');
if (access(left, 'type') === 'MemberExpression'
&& access(left, 'object.object.name') === 'String'
&& access(left, 'property.name') === 'startsWith'
&& legalExpression.indexOf('startsWith') < 0) {
legalExpression.push('startsWith');
context.report({
node: node,
message: 'String.prototype.startsWith is override'
});
}
}
}
}
}
},
rulesConfig: {
'caught-dangerous-call': 2,
'caught-override': 2
},
configs: {
recommended: {
rules: {
'test/caught-dangerous-call': 'error',
'test/caught-override': 'error'
}
}
}
}
function access(root, path) {
let objectToString = Object.prototype.toString;
if (objectToString.call(root) !== '[object Object]' || !path) return undefined;
let r = Object.assign({}, root);
let paths = path.split('.');
let pathLen = paths.length;
let i;
const arraySuffixPattern = /(\w+)((\[\d+\])+)/g; // 匹配前缀和后缀
for (i = 0; i < pathLen; i++) {
// 访问的是个数组,如name[1][2]
if (arraySuffixPattern.test(paths[i])) {
let prefix = RegExp.$1; // name
if (objectToString.call(r[prefix]) === '[object Array]') {
// 获取下标值
let suffix = RegExp.$2; // '[1][2]'
let suffixIndex = []; // ['1', '2', '3']
const arrayIndexPattern = /\[(\d+)\]/g;
let m;
while ((m = arrayIndexPattern.exec(suffix)) !== null) {
if (m.index === arrayIndexPattern.lastIndex) {
arrayIndexPattern.lastIndex++;
}
suffixIndex.push(RegExp.$1);
}
// 根据下标值访问数组
let j = 0;
let a = r[prefix];
let len = suffixIndex.length;
while (j < len && a !== undefined) {
a = a[suffixIndex[j]];
j++;
}
r = a;
} else {
return undefined;
}
} else {
if (r === undefined) {
return r;
}
if (objectToString.call(r[paths[i]]) === '[object Object]') {
r = r[paths[i]];
} else {
if (i === pathLen - 1) {
return r[paths[i]];
} else {
return undefined;
}
}
}
}
return r;
}
package.json
"scripts": {
"lint": "standard"
},
"standard": {
"plugin": [
"test"
],
"ignore": [
"tests/",
"test/",
"theme/"
]
}
使用
npm run lint
遇到的问题
console.log('test')已输出, 但没有输出‘CallExpression’ 和'AssignmentExpression'.即rule并没有被使用