Prevent use of unsupported JavaScript features in IE11 using ESLint?

Viewed 1698

I have an existing ESLint configuration with "ecmaVersion" set to "5" that I want to modify to allow the use of let and const which are ES6 features. There are mostly* supported in Internet Explorer 11. However, I want to reject the use of any ES6 features that aren't supported in IE11, e.g. classes. How can I do that with ESLint?

I did find the eslint-plugin-ie11 plug-in, but it only covers a few unsupported features.

*I would also like to block the use of let in loops, which is not supported in IE11.

1 Answers

you can add eslint rules to disallow pretty much any language feature you want using the no-restricted-syntax rule.

from 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

so, for example, if you wanted to block usage of arrow functions, template literals, and let/const declarations in the left side of for...in and for...of loops,

you could add this to the rules section of your 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"
]

then, running eslint on this file

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;

gives these errors:

  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)

and running eslint on this file

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; }

gives no errors

doing this for all es6 features would be more or less the same, just with a lot more selectors

Related