前提
react配置导入根路径需要在webpack中配置,但使用脚手架创建的项目,默认将babel
、webpack
等内容全部封装到react-scripts
中,所以在这种状态下没有办法更改webpack
中的内容
需要执行npm run eject
解开react-scripts
包
npm run eject
命令无法撤销- 执行后,会出现
config
和scripts
两个文件夹
方法
在新出现的config
文件夹中,找到 webpack.config.js
文件,在alias
中插入'@': path.resolve('src'),
就可以了
alias: {
'@': path.resolve('src'),
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
// Allows for better profiling with ReactDevTools
...(isEnvProductionProfile && {
'react-dom$': 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
}),
...(modules.webpackAliases || {}),
},
在以后引入时,#
代表的就是 根目录/src
了