Craco(Create React App Configuration Override)是一个用于扩展 Create React App(CRA)配置的工具。通过 Craco,你可以在不弹出 Create React App 的内部配置的情况下,轻松地对 CRA 的配置进行自定义。
craco配置文档:https://github.com/dilanx/craco/blob/main/packages/craco/README.md#configuration
craconpm i -D @craco/craco
craco 的配置文件:craco.config.js,并在配置文件中配置路径别名,代码如下:const path = require('path')
module.exports = {
// webpack 配置
webpack: {
// 配置别名
alias: {
// 约定:使用 @ 表示 src 文件所在路径
'@': path.resolve(__dirname, 'src')
}
}
}
package.json 中的脚本命令在 packge.json 文件中将以下代码
"scripts": {
"start": "react-scripts start"
"build": "react-scripts build"
"test": "react-scripts test"
"eject": "react-scripts eject"
}
修改成:
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "react-scripts eject"
},
在项目根目录创建 jsconfig.json 或者 tsconfig.json 配置文件,代码如下:
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
}
}
}
注意: 如果是 TS 没有先配置 tsconfig.json 直接用@会报如下错:
