忽略eslint错误:'import'和'export'只能出现在顶层。

66

是否有可能在eslint中禁用此错误?

Parsing error: 'import' and 'export' may only appear at the top level

2
这看起来像是一个无法修复的情况。请参见 https://github.com/eslint/eslint/issues/2259 和 https://github.com/eslint/espree/issues/124;特别是在124末尾开发者的引用,他基本上认为没有理由支持无效语法。 - Paul
4个回答

91

ESLint本身不支持此功能,因为这与规范相违背。但是如果您使用babel-eslint解析器,则可以在eslint配置文件中进行如下设置:

{
  "parser": "babel-eslint",
  "parserOptions": {
    "sourceType": "module",
    "allowImportExportEverywhere": true
  }
}

文档参考:https://github.com/babel/babel-eslint#configuration


1
似乎不需要使用babel-eslint。 - tjb
1
非顶层导入现在已成为规范的一部分,并且被广泛使用。 - Merc
现在它已经被esline检查支持了我的答案 - Luizgrs

35

如果其他方法不起作用,这是我的解决方案

"parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module"
}

20

eslint 6.2中增加了对动态导入的支持。

不过,您需要将ecmaVersion设置为11(或2020)。

"parserOptions": {
    "ecmaVersion": 11
    ...
}

你可以在他们的


会像这样工作吗? "eslintConfig": { "extends": "react-app", "parserOptions": { "ecmaVersion": 11 } }, - Steven Matthews
3
单单这样做对我没有用,我还需要添加以下代码 - "sourceType": "module" - Roger Heathcote
在在线演示中,使用 sourceType: script 是有效的。 - Luizgrs
这是一个更加更新的答案。 - College Code

4
在我的情况下: 为一个React项目添加javascriptreact。我猜这个项目类型应该被添加到插件中。
{
...,
 "plugins": [
        "prettier",
        "javascriptreact"
    ],
...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接