我有一个现有的 ESLint 配置,其中“ecmaVersion”设置为“5”,我想修改它以允许使用 ES6 功能 let 和 const。 Internet Explorer 11 支持大多数*。但是,我想拒绝使用 IE11 不支持的任何 ES6 功能,例如类。我怎样才能用 ESLint 做到这一点?
我确实找到了 eslint-plugin-ie11 插件,但它只涵盖了一些不支持的功能。
*我还想阻止在循环中使用let,这在IE11中不支持。
no-restricted-syntax
规则添加 eslint 规则来禁止几乎任何您想要的语言功能。
来自 eslint 文档
此规则允许您配置要限制使用的语法元素
...
...
您可以在 GitHub 上找到可以使用的 AST 节点名称的完整列表,并使用 AST Explorer 和 espree 解析器来查看您的代码由什么类型的节点组成。 ... 您还可以指定 AST 选择器 进行限制,从而可以更精确地控制语法模式。
...
该规则采用一个字符串列表,其中每个字符串都是一个 AST 选择器 ... [, or] 对象,其中指定选择器和可选的自定义消息
因此,例如,如果您想阻止使用箭头函数、模板文字以及let
const
和
for
...左侧的
in
/
for
声明of
循环,您可以将其添加到 eslintrc 的规则部分:"no-restricted-syntax": ["error",
{
"selector": "*:matches(ForOfStatement, ForInStatement) > VariableDeclaration.left:matches([kind=let], [kind=const])",
"message": "let/const not allowed in lhs of for..in / for..of loops."
},
{
"selector": "TemplateLiteral",
"message": "template literal strings not allowed"
},
"ArrowFunctionExpression"
]
然后,在此文件上运行 eslint
for(const x of foo) {}
for(let x of foo) {}
for(const x in foo) {}
for(let x in foo) {}
console.log(`hello world`);
const bar = x => x + 1;
给出这些错误:
1:5 error let/const not allowed in lhs of for..in / for..of loops no-restricted-syntax
2:5 error let/const not allowed in lhs of for..in / for..of loops no-restricted-syntax
3:5 error let/const not allowed in lhs of for..in / for..of loops no-restricted-syntax
4:5 error let/const not allowed in lhs of for..in / for..of loops no-restricted-syntax
5:13 error template literal strings not allowed no-restricted-syntax
6:13 error Using 'ArrowFunctionExpression' is not allowed no-restricted-syntax
✖ 6 problems (6 errors, 0 warnings)
并在此文件上运行 eslint
let a = 1;
const b = 2;
for(var x of foo) {}
for(var x in foo) {}
console.log('hello world');
function bar(x) { return x + 1; }
没有错误
对
所有es6 功能执行此操作或多或少是相同的,只是有更多的选择器
要配置 ESLint 以允许使用 let 和 const,同时阻止其他不受支持的 ES6 功能(例如类和阻止 let 循环),您可以结合使用 ESLint 核心规则和自定义规则/插件。以下是如何配置 ESLint 设置的示例: