在 VSCode 中如何正确配置 jsconfig.json 以便使用 index.js 导入的绝对路径工作?

Dim*_*nis 5 javascript import path reactjs visual-studio-code

在我的 React 项目中,./根目录在哪里,我已经配置了 webpack,以便我可以从我的./src目录中导入任何文件。

例如,考虑以下目录结构:

./
|-src/
| |-components/
| | |-Button/
| | | |-index.js
| | | |-Button.jsx
Run Code Online (Sandbox Code Playgroud)

其中src/components/Button/index.js仅包含以下内容:

export { default } from './Button';

现在假设我在 中创建了另一个组件src/components/NewComponent,其结构类似于src/components/Button,但在我的内部我NewComponent.jsx正在执行以下操作:

import Button from 'components/Button'

上面的编译很好,因为我已经正确设置了我的 webpack。

我想什么是能够做到的,是VSCode能够带我去定义Button组件时,我alt+click对这个词Button的的import发言,并带我到index.js文件的内容时,我alt+clickcomponents/Button一部分。

我似乎无法做到这一点。

jsconfig.json在撰写本文时,我的情况如下:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "baseUrl": "./",
    "paths": {
      "src/*": ["./src/*"]
    }
  },
  "exclude": ["node_modules", "build", "dist"]
}
Run Code Online (Sandbox Code Playgroud)

而且,为了更好的衡量,我的 webpack 配置的相关部分:

const PATHS = {
  node_modules: path.resolve(__dirname, 'node_modules'),
  src: path.resolve(__dirname, 'src'),
  style: path.resolve(__dirname, 'style'),
  assets: path.resolve(__dirname, 'assets'),
  test: path.resolve(__dirname, 'test')
};

module.exports = {
  resolve: {
    modules: [
      path.resolve(__dirname),
      PATHS.node_modules,
      PATHS.src,
      PATHS.style,
      PATHS.assets,
      PATHS.test
    ],
    mainFiles: ['index', 'index.js', 'index.jsx', 'index.scss'],
    extensions: ['.jsx', '.js', '.json', '.scss', '.css']
  },
....
Run Code Online (Sandbox Code Playgroud)

Tom*_*a5o 3

我认为您的配置是正确的,您犯的唯一错误是路径设置

\n\n

尝试这个:

\n\n
{\n  "compilerOptions": {\n    "target": "es6",\n    "module": "commonjs",\n    "baseUrl": "./",\n    "paths": {\n      "components/*": ["./src/components/*/index"]\n    }\n  },\n  \xe2\x80\x9cInclude\xe2\x80\x9d: [\xe2\x80\x9c./src/**/*\xe2\x80\x9d],\n  "exclude": ["node_modules", "build", "dist"]\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者只是输入import Button from \'src/components/Button\'

\n\n

关闭后重新打开项目 et voil\xc3\xa0 ;)

\n