前几天在鼓捣react的小项目的时候发现antd官网没有介绍npm run eject之后的按需加载antd和自定义主题。所以想写篇文章来记录一下。
1、官网的办法
- npm install craco craco-less
- 修改package.json文件
/* package.json */
"scripts": {
- "start": "react-scripts start",
- "build": "react-scripts build",
- "test": "react-scripts test",
+ "start": "craco start",
+ "build": "craco build",
+ "test": "craco test",
}
- 然后在项目根目录创建一个 craco.config.js 用于修改默认配置。
- 修改 craco.config.js 文件如下。
const CracoLessPlugin = require('craco-less');
module.exports = {
plugins: [
{
plugin: CracoLessPlugin,
options: {
lessLoaderOptions: {
modifyVars: { '@primary-color': '#1DA57A' },
javascriptEnabled: true,
},
},
},
],
};
该方法适用于没有npm run eject
2、npm run eject之后
- 安装balbel-plugin-import插件
- npm i babel-plugin-import --save
- 修改package.json文件
"babel": {
"presets": [
"react-app"
],
"plugins": [
[
"import",
{
"libraryName": "antd",
"style": true (true代表引入less文件,还有选项值为css)
}
]
]
},
找到config/webpack.config.js文件
- 在第51行左右添加下面的代码
// 这是原本就存在的
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
// 这是添加的
const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;
- 在第500行左右添加下面代码
// 原本的代码
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 3,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: {
getLocalIdent: getCSSModuleLocalIdent,
},
},
'sass-loader'
),
},
// 从这里开始添加
{
test: lessRegex,
exclude: lessModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
},
'less-loader'
),
sideEffects: true,
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: lessModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: true,
getLocalIdent: getCSSModuleLocalIdent,
},
'less-loader'
),
},
最重要的一步来了,搜索preProcessor,找到该区域
添加下面的代码,结果如下:
{
loader: require.resolve('less-loader'),
options: {
lessOptions: { //如果使用less-loader@5,请移除 lessOptions 这一级直接配置选项。
modifyVars: { '@primary-color': '#1DA57A' },
javascriptEnabled: true,
}
}
}
重新运行npm start,会发现antd的theme已经发生变化,也会自动引入用到的antd文件。