使用 CRA 脚手架创建的项目,如果想要修改编译配置,通常可能会选择
npm run eject
弹出配置后魔改。但是,eject 是不可逆操作,弹出配置后,你将无法跟随官方的脚步去升级项目的react-script
版本。
如果想要无 eject 重写 CRA 配置,一般可以有以下几种方式:
- 通过 CRA 官方支持的
--scripts-version
参数,创建项目时使用自己重写过的react-scripts
包- 使用
react-app-rewired + customize-cra
组合覆盖配置- 使用
craco
覆盖配置
在 AntDesign 官方文档中,已经推荐使用 craco
来覆写相关 webpack 配置;
# 安装 @craco/craco
yarn add @craco/craco
由于 CRA 脚手架默认不支持 less
,所以需要通过拓展来实现:
# 安装 craco-less 包,支持覆写 webpack loader 相关配置
yarn add craco-less -D
# 同时需要安装 less 和 less-loader
yarn add less less-loader -D
项目根目录下新建一个 craco.config.js
文件:
const CracoLessPlugin = require("craco-less");
module.exports = {
plugins: [
{
plugin: CracoLessPlugin,
options: {
lessLoaderOptions: {
lessOptions: {
modifyVars: {
},
javascriptEnabled: true,
},
},
},
},
],
};
问题来了:如果要支持 css-modules ,该如何处理?
在实践时,按照官方提供的文档,没法实现支持 css-modules
的功能,官方文档提供的配置方法如下:
const CracoLessPlugin = require("craco-less");
module.exports = {
plugins: [
{
plugin: CracoLessPlugin,
options: {
cssLoaderOptions: {
modules: {
localIdentName: "[local]_[hash:base64:5]" },
},
},
},
],
};
如果需要解决这个问题,这里有两个方案:
方案一:继续使用 craco-less
来进行配置,但是需要新增一个配置选项,配置代码如下所示:【推荐】
// craco.config.js
const CracoLessPlugin = require("craco-less");
const lessModuleRegex = /\.module\.less$/;
module.exports = {
plugins: [
{
plugin: CracoLessPlugin,
options: {
// less loader options
lessLoaderOptions: {
lessOptions: {
modifyVars