使用配置了jsconfig.json的路径映射时,解决导入时的eslint错误

27

这是我的项目结构:

-src

--assets
--components
--constants
--helpers
--pages
--routes

eslintrc.json
jsconfig.json
App.js
index.js

我厌倦了:

import SomeComponent from '../../../../../components/SomeComponent';

我想这样做:

import SomeComponent from '@components/SomeComponent';

所以我在 Stack Overflow 上看到了这个问题:

VSCode Intellisense does not work with webpack + alias

然后我使用以下方法解决了问题:

jsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "es6",
    "module": "commonjs",
    "paths": {
      "@components/*": ["./src/components/*"]
     }
  }
}

但是 eslint 现在抱怨说它未解析,尽管它编译得很好。

eslint 错误:

无法解析模块路径 '@components/SocialMedia'.eslint(import/no-unresolved)

注:

我不想禁用 eslint。我想让它也理解这种路径。

3个回答

41

一种替代方法,假设您已经安装了eslint-plugin-import(在您的devDependencies中)。只需在您的.eslintrc.json文件中添加此“设置”。

.eslintrc.json

{
  "settings": {
    "import/resolver": {
      "node": {
        "moduleDirectory": ["node_modules", "src/"]
      }
    }
  }
}

jsconfig.json

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

然后你只需要调用:

import SomeComponent from 'components/SomeComponent';`

1
这个解决方案适用于 src 目录下的文件。然而,对于根目录下的文件,eslint 无法解析路径。如何解决这个问题? - StangSpree
1
似乎eslint和jsconfig应该可以很好地协同工作,因此您不需要这样做,但也许我还没有完全掌握jsconfig的目的。您的答案对我有用,谢谢! - Brady Dowling
这个方法可行,但我失去了 ⌘ +click 即跳转到定义的功能,而这是我经常用来在文件之间跳转的。有什么建议吗?(我也不在一个 TS 项目中) - KeshavDulal
@StangSpree,你可以使用moduleDirectory: ['node_modules', './'],但是现在你需要添加一个src前缀来导入上面示例中相同的组件。 - ShadyStego

22

我已经安装了:

npm install -D eslint-import-resolver-alias

并将其添加到我的 ESLint 配置文件中:

eslintrc.json

"settings": {
    "import/resolver" : {
      "alias" : {
        "map" : [
          ["@components","./src/components/"]
        ],
        "extensions": [".js"]
      }
    }
  }

现在它正在运行,eslint不再显示错误。

编辑:

我正在使用webpack,还需要执行以下操作:

webpack.config.js

resolve: {
    alias: {
      '@components': path.resolve(__dirname, 'src/components/')
    }
  }

1
这个解决方案适用于 src 目录下的文件。然而,对于根目录下的文件,eslint 无法解析路径。如何解决这个问题? - StangSpree

5

针对lerna用户:

eslintrc

{
  "settings": {
    "import/parsers": {
      "@typescript-eslint/parser": [".js", ".jsx", ".ts", ".tsx"]
    },
    "import/resolver": {
      "node": {
        "extensions": [".js", ".jsx", ".ts", ".tsx"],
        // this resolves path alias import problems
        "moduleDirectory": [ "apps/*/src", "packages/*/src" ]
      },
      "typescript": {
        "alwaysTryTypes": true,
        // this resolves packages import problems
        "project": [
          "packages/*/tsconfig.json", 
          "apps/*/tsconfig.json"
        ]
      }
    }
  }
}

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