繁体   English   中英

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

[英]Prevent use of unsupported JavaScript features in IE11 using ESLint?

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

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

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

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

来自eslint 文档

此规则允许您配置要限制使用的语法元素
...
您可以在 GitHub 上找到可以使用的 AST 节点名称的完整列表,并使用AST Explorer和 espree 解析器查看您的代码包含哪些类型的节点。
...
您还可以指定要限制的AST 选择器,从而可以更精确地控制语法模式。
...
此规则采用字符串列表,其中每个字符串是一个 AST 选择器 ... [, or] 对象,其中指定了选择器和可选的自定义消息

因此,例如,如果您想在for ... infor ... of循环的左侧阻止使用箭头函数、模板文字和let / const声明,

您可以将其添加到 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 功能执行此操作或多或少是相同的,只是有更多的选择器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM