VSCode ESLint 如何修复解析错误:'import' 和 'export' 可能只出现在顶层

Gob*_*ins 0 javascript ecmascript-6 eslint babeljs visual-studio-code

注意:代码正在运行,只有 ESLint 给了我一个我想修复的错误!!

进行动态导入时:

if (true) import x from 'y'; //Parsing error: 'import' and 'export' may only appear at the top level
Run Code Online (Sandbox Code Playgroud)

我的.eslintrc

{
  "root": true,
  "extends": "eslint:recommended",
  "env": {
    "es6": true,
    "node": true,
    "browser": true
  },
  "parserOptions": {
    "ecmaVersion": 10,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "rules": {
    "strict": 0,
    "no-undef": 2,
    "accessor-pairs": 2,
    "comma-dangle": [2, "always-multiline"],
    "consistent-return": 2,
    "dot-notation": 2,
    "eqeqeq": 2,
    "indent": [2, 2, {"SwitchCase": 1}],
    "no-cond-assign": 2,
    "no-constant-condition": 2,
    "no-eval": 2,
    "no-inner-declarations": [0],
    "no-unneeded-ternary": 2,
    "radix": 2,
    "semi": [2, "always"],
    "camelcase": 2,
    "comma-spacing": 2,
    "comma-style": 2,
    "eol-last": 2,
    "linebreak-style": [2, "unix"],
    "new-parens": 2,
    "no-lonely-if": 2,
    "no-multiple-empty-lines": 2,
    "no-nested-ternary": 2,
    "no-spaced-func": 2,
    "no-trailing-spaces": 2,
    "operator-linebreak": 2,
    "quotes": [2, "single"],
    "semi-spacing": 2,
    "space-unary-ops": 2,
    "arrow-parens": 2,
    "arrow-spacing": 2,
    "no-class-assign": 2,
    "no-dupe-class-members": 2,
    "no-var": 2,
    "object-shorthand": 2,
    "prefer-const": 2,
    "prefer-spread": 2,
    "prefer-template": 2
  },
Run Code Online (Sandbox Code Playgroud)

我已经尝试过:
...切换ecmaVersion到 11, 2018, 2019, 2020 这给了我错误的数字或解析器不再工作
......添加parser: babel-eslint这使解析器不再工作
......添加allowImportsExportsAnywhere: true它什么也没做

Mar*_*ark 12

https://eslint.org/blog/2019/08/eslint-v6.2.0-released#highlights

此版本增加了对 ES2020 语法的支持,其中包括对动态导入和 BigInt 的支持。这可以ecmaVersion: 2020在您的配置文件中启用。

这似乎建议将其添加到您的.eslintrc.json文件中并重新加载 vscode:

"parserOptions": {
  "ecmaVersion": 2020,
  "sourceType": "module",
  "ecmaFeatures": {
    "jsx": true
  }
},
Run Code Online (Sandbox Code Playgroud)

或者"ecmaVersion": 11, 是同一件事。

但是ecmaVersion当我这样做时,我得到了一个关于无效的不同错误选项。 这似乎消除了该错误

"env": {
    "browser": true,
    "node": true,
    "es2020": true
},
Run Code Online (Sandbox Code Playgroud)

没有ecmaVersionparserOptions 显然 vscode 的 eslint 版本尚不支持"ecmaVersion": 2020