ESlint导入/无解,Babel插件根导入

时间:2020-08-05 07:43:33

标签: typescript babeljs eslint

有人可以向我解释一下,为什么ESlint(VS Code,WebStorm)突出显示这种导入变体?

import UserBlock from '~/templates/UserBlock'; //js file 

.babelrc

"plugins": [
        [
            "babel-plugin-root-import",
            {
                "rootPathSuffix": "./src/",
                "rootPathPrefix": "~/"
            }
        ]
    ]

.eslintrc.js

module.exports = {
  settings: {
    'import/resolver': {
      'babel-plugin-root-import': {
        rootPathPrefix: '~',
        rootPathSuffix: 'src',
      },
    },
  },
};

1 个答案:

答案 0 :(得分:1)

根据文档的解决方案

根据我对“ babel-plugin-root-import”插件的经验,您应该将配置更改为:

"plugins": [[
  "babel-plugin-root-import",
    {
      "rootPathPrefix": "~"
      "rootPathSuffix": "src",
    }
 ]]

多余的斜杠(/和点(.)似乎使插件感到困惑。

但是...

不幸的是,“ babel-plugin-root-import”的eslint软件包目前没有得到很好的维护。根据您的eslintrc,您似乎使用的是eslint-import-resolver-babel-root-import软件包,因此您使用的是“ Don't let ESLint be Confused”。如果尚未安装该软件包,则可能要先尝试。

我当前正在尝试使用“ eslint-import-resolver-babel-root-import-fixed”分支,该分支是最近更新的。由于NPM命名冲突,其配置略有不同。在eslintrc文件中,您需要将babel-plugin-root-import替换为eslint-import-resolver-babel-root-import-fixed


可行的解决方案

说了这么多,我还没办法使它们起作用。使用babel进行编译时,没有任何问题,但是eslint会引发您所描述的错误。

过去几年中,我的解决方案是添加以下eslint规则:

"import/no-unresolved": [
  "error",
  {
    "ignore": [
      "^[~]",
    ]
  }
]

另一种方法

我使用babel-plugin-root-import是因为我们有多个根前缀。如果您只需要一个,我建议您研究babel-plugin-module-resolver,尽管may have its own set of problems。我过去也曾使用过“ Webpack模块别名”,尽管您可能无法使用。