使用 customize-cra 和 react-app-rewired 对React项目进行webpack配置的注入
yarn add customize-cra react-app-rewired -D
在项目根目录创建config-overrides.js和aliasPaths.json文件:
#config-overrides.js
const {
override,
addWebpackAlias,
fixBabelImports,
} = require("customize-cra");
const path = require("path");
module.exports = override(
// antd按需加载
fixBabelImports("import", {
libraryName: "antd",
libraryDirectory: "es",
style: true,
}),
//路径别名配置
addWebpackAlias({
["@components"]: path.resolve(__dirname, "src/components"),
["@config"]: path.resolve(__dirname, "src/config"),
["@store"]: path.resolve(__dirname, "src/store"),
["@utils"]: path.resolve(__dirname, "src/utils"),
["@service"]: path.resolve(__dirname, "src/service"),
["@api"]: path.resolve(__dirname, "src/api"),
["@lib"]: path.resolve(__dirname, "src/lib"),
["@pages"]: path.resolve(__dirname, "src/pages"),
})
);
#aliasPaths.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": ["types/*"],
"@components/*": ["src/components/*"],
"@config/*": ["src/config/*"],
"@store": ["src/store"],
"@utils/*": ["src/utils/*"],
"@service/*": ["src/service/*"],
"@api/*": ["src/api/*"],
"@lib": ["src/lib"],
"@pages/*": ["src/pages/*"],
}
}
}
修改tsconfig.json或jsconfig.json
{
...,
"extends": "./aliasPaths.json",
}
修改package.json
//GENERATE_SOURCEMAP=false 配置在unix或linux环境中可以明显加快打包速度
{
"scripts": {
"start": "react-app-rewired start",
"build": "GENERATE_SOURCEMAP=false react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
},
}