我一直在寻找一个 eslint 插件,它可以在通用变量/参数/函数名称上提供错误。我只找到相当乏味的答案(列出每个可能的符号而不进行模式匹配)或与命名样式有关的答案(例如驼峰式大小写)。这不是我要找的。
一些“太通用”的标识符/名称示例:
query
、result
和queryResult
data, data1, _data1, _getData(), _getDataInfo()
var, info, tmp
metadataInfo, meta, data, info
thing, whatever, boo, foo, blah, a, b
input, param, arg
response, total, ...
calculateBasePay(input)
一些前缀和其他单词的示例很好,除非与通用变量一起使用。
getData
setInfo
create, translate, manipulate, manage
一些可能增加复杂性的示例:
无论如何......我有一个半生不熟的解决方案,我将发布作为潜在的答案,但我对替代方案感兴趣。
这是我的部分解决方案。希望有更好的。
eslintrc.js 内部
const genericVariableNames = [
'arg', 'args', 'argument', 'count', 'counter', 'data', 'err', 'error',
'flag', 'foo', 'idx', 'index', 'info', 'information', 'item', 'key', 'message', 'meta', 'metadata',
'output', 'param', 'parameter', 'queries', 'query', 'record', 'result', 'status', 'stuff', 'junk',
'tmp', 'temp', 'temporary|temporaries', 'thing', 'thingy', 'thingies',
'val', 'value', 'var', 'variable',
]
const genericPrefixes = [ // these prefixes are fine, as long as a generic variable name isn't next.
'get', 'set', 'create', 'update', 'my', 'this', '_',
]
const genericVariableNamesPattern =
'(' + genericPrefixes.join('|') + ')?' + // optional prefix, prevents identifiers like 'getVar' without forbidding 'get'
'(' +
genericVariableNames.join('|') +
'(e?s)?' + // handle -es and -s plurals. Doesn't handle -ies plurals.
'\\d*' + // adding numbers won't make an identifier better, eg. tmp1, status2, etc.
')+' // Require AT LEAST ONE generic symbol; prevent chained generic names: tmpVar, resultVariable, argumentCounterVar;
const identifierWithGenericName = `Identifier[name=/^${genericVariableNamesPattern}$/i]`
const clarityGuidance = 'Names should be helpful even out of context (search-results/pasted/stacktrace/glimpse...)'
// ... inside the rules object...
'no-restricted-syntax': [
'error',
{
selector: `FunctionDeclaration ${identifierWithGenericName}`,
message: `Generic function names and parameters are not allowed. ${clarityGuidance}`,
},
{
selector: `VariableDeclarator > ${identifierWithGenericName}`,
message: `Generic variable names are not allowed. ${clarityGuidance}`,
},
{
selector: `ArrowFunctionExpression > AssignmentPattern > ${identifierWithGenericName}`,
message: `Generic arrow function parameter names are not allowed. ${clarityGuidance}`,
},
],