react, alias @

Some instructions for React scaffolding [Click here to view React scaffolding(/2019/08/17-react-2.html)

With the complexity of react apps, the inter-dependency references between components are becoming more and more complicated.

So it appeared
import xxx from ‘../../components/xxx’

import xxx from ‘../../../components/xxx’
Complex relative addresses

This indirect address is too complicated, and the relationship between the paths is not clear enough, but it increases the dependence on the path relationship

So we need to introduce webpack.resolve.alias function to simplify this kind of path relative relationship

1
2
3
4
5
6
7
8
9
10
11
12
├── package.json
├── ...
├── config
│ ├── ...
│ ├── webpack.config.js
│ └── ...
├── README.md
├── src
│ ├── components
│ ├── pages
│ ├── ...
│ ├── ...

The above is the react engineering structure, find the webpack configuration, and modify the alias configuration.

1
2
3
4
5
6
7
8
9
10
// ...
resolve: {
    ...
    alias: {
      '@components': path.resolve(__ dirname, '../src/components'),
      ...
    }
    ...
  },
// ...

After the above configuration, the dependency on components can be changed from

1
import Detail from '../../components/detail'

change into:

1
import Details from '@ components / detail'

Handle component relative address aliases perfectly

Persist in original technology sharing, your support will encourage me to continue to create!