首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >ESLint如何修复解析错误:“导入”和“导出”只能出现在顶层

ESLint如何修复解析错误:“导入”和“导出”只能出现在顶层
EN

Stack Overflow用户
提问于 2020-02-21 12:44:48
回答 3查看 13.3K关注 0票数 4

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

执行动态导入时:

代码语言:javascript
运行
复制
if (true) import x from 'y'; //Parsing error: 'import' and 'export' may only appear at the top level

我的.eslintrc

代码语言:javascript
运行
复制
{
  "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
  },

我已经试过了

...switching ecmaVersion to,11,2018,2019,2020

使解析器不再工作的...added parser: babel-eslint

...added allowImportsExportsAnywhere: true什么都没做

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-02-21 17:26:56

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

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

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

代码语言:javascript
运行
复制
"parserOptions": {
  "ecmaVersion": 2020,
  "sourceType": "module",
  "ecmaFeatures": {
    "jsx": true
  }
},

或者"ecmaVersion": 11,,这也是一样的东西。

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

代码语言:javascript
运行
复制
"env": {
    "browser": true,
    "node": true,
    "es2020": true
},

显然,vscode版本的ecmaVersion parserOptions**!**中的和no 还不支持"ecmaVersion": 2020

票数 24
EN

Stack Overflow用户

发布于 2020-02-21 12:52:53

也许你可以在这个结构中使用

代码语言:javascript
运行
复制
const x =
  your condition ? require("y") : () => null;

在您的组件中

代码语言:javascript
运行
复制
{ your condition ?(<x/>):("")}
票数 1
EN

Stack Overflow用户

发布于 2020-02-21 12:52:03

看来语法是错的。试试这个:

代码语言:javascript
运行
复制
if (true) 
  import('y').then((x) => {
     console.log(x);
  });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60338944

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档