react使用craco优雅地配置别名
目录
1、新建craco.config.js文件
2、新建path.tsconfig.json(路径配置)文件
3、接下来需要在tsconfig.json中引入path.tsconfig.json文件
4、package.json修改启动命令
5、引入测试
6、重启项目:不要忘记!!
7、其他
1、新建craco.config.js文件
module.exports = {
webpack: {
alias: {
//使用 @ 表示 src 文件所在路径
"@": resolve("src"),
"components": resolve("src/components"),
}
}
}
2、新建path.tsconfig.json(路径配置)文件
将下方代码复制进去,需要注意的是"components/*":["src/components/*"],不能丢失src
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@/*": ["src/*"],
"components/*":["src/components/*"]
}
}
}
3、接下来需要在tsconfig.json中引入path.tsconfig.json文件
"extends": "./path.tsconfig.json",
4、package.json修改启动命令
修改为
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "react-scripts eject"
},
5、引入测试
6、重启项目:不要忘记!!
7、其他
第3步和第4步可以合并起来,直接在tsconfig.json直接写,或者可以描述为替换这两步
"baseUrl": "./",
"paths": {
"@/*": ["src/*"],
"components/*":["src/components/*"]
},