gpt4 book ai didi

javascript - 使用 ESLint 防止在 IE11 中使用不受支持的 JavaScript 功能?

转载 作者:数据小太阳 更新时间:2023-10-29 04:51:51 26 4
gpt4 key购买 nike

我有一个现有的 ESLint 配置,“ecmaVersion”设置为“5”,我想修改它以允许使用 letconst,它们是 ES6 特性。 Internet Explorer 11 支持大多数*。但是,我想拒绝使用 IE11 不支持的任何 ES6 功能,例如类。我如何使用 ESLint 做到这一点?

我确实找到了 eslint-plugin-ie11 插件,但它只涵盖了一些不受支持的功能。

*我还想阻止 let in 循环的使用,这在 IE11 中不受支持。

最佳答案

您可以使用 no-restricted-syntax 添加 eslint 规则来禁止几乎所有您想要的语言功能规则。

来自 the eslint docs

this rule allows you to configure the syntax elements you want to restrict use of
...
You may find the full list of AST node names you can use on GitHub and use AST Explorer with the espree parser to see what type of nodes your code consists of.
...
You can also specify AST selectors to restrict, allowing much more precise control over syntax patterns.
...
This rule takes a list of strings, where each string is an AST selector...[, or] objects, where the selector and an optional custom message are specified

因此,例如,如果您想在 for< 的左侧阻止使用箭头函数、模板文字和 let/const 声明...infor...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 特性做这个或多或少是一样的,只是有更多的选择器

关于javascript - 使用 ESLint 防止在 IE11 中使用不受支持的 JavaScript 功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53160669/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com