no-restricted-syntax
禁用指定的语法
JavaScript 有很多语言特性,并非每个人都喜欢所有这些特性。因此,一些项目选择完全禁止使用某些语言特性。例如,您可能决定禁止使用 try-catch
或 class
,或者您可能决定禁止使用 in
运算符。
与其为您想要关闭的每个语言特性创建单独的规则,不如使用此规则来配置您想要限制使用的语法元素。对于 JavaScript 语言,这些元素由它们的 ESTree 节点类型表示。例如,函数声明由 FunctionDeclaration
表示,而 with
语句由 WithStatement
表示。您可以使用 代码浏览器 来确定表示您的代码的节点。
您还可以指定 AST 选择器 来限制,从而可以更精确地控制语法模式。
注意:此规则可以与您使用 ESLint Lint 的任何语言一起使用。要查看您的另一种语言的代码由什么类型的节点组成,您可以使用
- typescript-eslint Playground 如果您将 ESLint 与
typescript-eslint
一起使用。 - ESLint 代码浏览器 如果您使用 ESLint 来 Lint JavaScript、JSON、Markdown 或 CSS。
规则详情
此规则禁止指定的(即用户定义的)语法。
选项
此规则接受字符串列表,其中每个字符串都是一个 AST 选择器
{
"rules": {
"no-restricted-syntax": ["error", "FunctionExpression", "WithStatement", "BinaryExpression[operator='in']"]
}
}
或者,该规则也接受对象,其中指定了选择器和可选的自定义消息
{
"rules": {
"no-restricted-syntax": [
"error",
{
"selector": "FunctionExpression",
"message": "Function expressions are not allowed."
},
{
"selector": "CallExpression[callee.name='setTimeout'][arguments.length!=2]",
"message": "setTimeout must always be invoked with two arguments."
}
]
}
}
如果在 message
属性中指定了自定义消息,则 ESLint 将在报告 selector
属性中指定的语法出现时使用该消息。
字符串和对象格式可以根据需要在配置中自由混合。
对于具有 "FunctionExpression", "WithStatement", BinaryExpression[operator='in']
选项的此规则的错误代码示例
/* eslint no-restricted-syntax: ["error", "FunctionExpression", "WithStatement", "BinaryExpression[operator='in']"] */
const doSomething = ;
;
对于具有 "FunctionExpression", "WithStatement", BinaryExpression[operator='in']
选项的此规则的正确代码示例
/* eslint no-restricted-syntax: ["error", "FunctionExpression", "WithStatement", "BinaryExpression[operator='in']"] */
me.dontMess();
function doSomething() {};
foo instanceof bar;
何时不使用它
如果您不想限制您的代码使用任何 JavaScript 功能或语法,则不应使用此规则。
相关规则
版本
此规则在 ESLint v1.4.0 中引入。