安装依赖
yarn add antd
yarn add react-app-rewired customize-cra babel-plugin-import
yarn add less less-loader
在根目录下配置config-overrides.js
const {override,fixBabelImports,addLessLoader} =require('customize-cra');
module.exports = override(
// 按需打包
fixBabelImports('import',{
libraryName:'antd',
libraryDirectory:'es',
style:true,//自动打包相关的样式 默认为 style:'css'
}),
// 设置antd自定义主题
addLessLoader({
javascriptEnabled: true,
modifyVars:{'@primary-color':'#1DA57A'},
})
);
修改packge.json 的配置文件
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react--app-rewired test",
"eject": "react-scripts eject"
},
然后就报错
ValidationError: Invalid options object. Less Loader has been initialized using an options object that does not match the API schema.
- options has an unknown property ‘modifyVars’. These properties are valid:
object { lessOptions?, prependData?, appendData?, sourceMap?, implementation?
查找了相关文档发现,新版本写法已经发生改变,下面翻译过来就是css-loader配置格式(从布尔值转换为的选项lessOptions)已在custom-cra的运行和构建过程中引起错误,
原来addLessLoader的配置选项现在将嵌套在一个lessOptions对象中
解决方式
将addLessLoader的配置选项现在将嵌套在一个lessOptions对象中
const {override,fixBabelImports,addLessLoader} =require('customize-cra');
module.exports = override(
fixBabelImports('import',{
libraryName:'antd',
libraryDirectory:'es',
style:true,
}),
addLessLoader({
lessOptions:{
javascriptEnabled:true ,
ModifyVars:{ '@primary-color':'#eee' }
}
})
);
官方文档
https://github.com/arackaf/customize-cra
https://github.com/arackaf/customize-cra/issues/253