简体   繁体   中英

In VSCode how to properly configure jsconfig.json in order for absolute paths with index.js imports to work?

In my React project, where ./ is the root directory, I have configured webpack so that I can import any file from within my ./src directory.

For example, consider the following directory structure:

./
|-src/
| |-components/
| | |-Button/
| | | |-index.js
| | | |-Button.jsx

where src/components/Button/index.js contains just this:

export { default } from './Button';

Now let's say I create another component in src/components/NewComponent , which is structured similarly to src/components/Button , but inside my NewComponent.jsx I am doing the following:

import Button from 'components/Button'

The above compiles just fine because I have set up my webpack correctly.

What I would like to be able to do, is for VSCode to be able to take me to the definition of the Button component when I alt+click on the word Button of the import statement, and take me to the index.js file's contents when I alt+click on the components/Button part.

I cannot seem to be able to do that.

My jsconfig.json is the following, as of the time of writing:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "baseUrl": "./",
    "paths": {
      "src/*": ["./src/*"]
    }
  },
  "exclude": ["node_modules", "build", "dist"]
}

And, for good measure, the relevant part of my webpack config:

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']
  },
....

I think your configuration is correct the only mistake you've made is in the path setting.

Try this:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "baseUrl": "./",
    "paths": {
      "components/*": ["./src/components/*/index"]
    }
  },
  “Include”: [“./src/**/*”],
  "exclude": ["node_modules", "build", "dist"]
}

or just type import Button from 'src/components/Button'

after this close-reopen the project et voilà ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM