【问题标题】:ESlint import/no-unresolved with Babel plugin root importESlint import/no-unresolved with Babel plugin root import
【发布时间】:2020-11-25 08:34:44
【问题描述】:

谁能解释一下,为什么 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',
      },
    },
  },
};

【问题讨论】:

  • ~ 指的是您的主目录。你应该在你的项目中使用绝对的东西,比如/
  • @japrescott - 你的意思是我应该把这个目录自己添加到配置中,并且只能在“~”中使用波浪号而没有任何子文件夹?
  • 不,我是说您不应该在任何配置中使用 Tilde/~,因为这肯定在您的项目之外。用./替换所有~
  • @japrescott 在babel-plugin-root-import 的上下文中,~ 用作项目根目录的别名。所以,你不用../../../src/web/comp/xyz,而是写~/src/web/comp/xyz,然后 babel 会计算出剩下的部分。该插件[建议波浪号指向您的项目根目录][github.com/entwicklerstube/babel-plugin-root-import#config],它与用户主目录的 shell 别名没有实际关系。
  • @PatFowler 感谢您让我知道这是一个“功能”! :)

标签: typescript babeljs eslint


【解决方案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 Module Aliases”,但您可能无法使用。

【讨论】:

    猜你喜欢
    • 2019-10-05
    • 1970-01-01
    • 2021-08-22
    • 2022-06-24
    • 2021-03-13
    • 2020-04-12
    • 2020-07-16
    • 2019-06-21
    • 1970-01-01
    相关资源
    最近更新 更多