简体   繁体   中英

how can i shorten my imports as import xxx from “@dir/subdir/file” in react

I have configured my jsconfig.json in my root directory as:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@dir/*": ["./src/app/dir/*"]
    }
  },
  "exclude": ["node_modules", "**/node_modules/*"],
}

my folder structure looks as follows:

root  
│
└───src
│   |__app
|   |    |__dir 
|   |    |    |__subdir1 
|   |    |    |     |__file1.js and other js files
|   |    |    |__subdir2
|   |    |          |__file2.js
|
|__jsconfig.json
|__package.json
|__...other root files 


my goal is to import something from file 1 to file 2 using

import xyz from '@dir/subdir1/file1'

instead of using

import xyz from '../subdir1/file1'

Make sure your webpack config webpack.config.js eventually has:

For CRA after ejecting your webpack config, you should be able to navigate to webpack.config.js and add your alias to the list.

 resolve {
     alias: {
       "@dir": "src/app/dir"
    },
 }

or in Next.js next.config.js

 config.resolve.alias = {
   ...config.resolve.alias,
   "@dir": "src/app/dir"
};

Check out this documentation: https://webpack.js.org/configuration/resolve/

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