在使用React开发项目,使用第三方UI库antd时,引入antd文件,每次加载时,把一些不需要的也加载上了,这是没有必要的,所以就需要配置一下antd文件,是她能够按照需要引入对应的文件,写次文章,作为记录,方便日后自己再次使用方便。
第一步:自定义配置
指令:npm i creat-app-rewired customize-cra
第二步:配置json文件
/* package.json */
"scripts": {
- "start": "react-scripts start",
+ "start": "react-app-rewired start",
- "build": "react-scripts build",
+ "build": "react-app-rewired build",
- "test": "react-scripts test",
+ "test": "react-app-rewired test",
}
*注:‘-’为删除的意思,“+”为添加的意思,上边的代码意思就是把第一行替换为第二行,以此类推。
*第三步:然后在项目根目录创建一个 config-overrides.js 用于修改默认配置。
module.exports = function override(config, env) {
// do stuff with the webpack config...
return config;
};
第四步:使用 babel-plugin-import
npm i bable-plugin-import
第五步:修改config文件
+ const { override, fixBabelImports } = require('customize-cra');
- module.exports = function override(config, env) {
- // do stuff with the webpack config...
- return config;
- };
+ module.exports = override(
+ fixBabelImports('import', {
+ libraryName: 'antd',
+ libraryDirectory: 'es',
+ style: 'css',
+ }),
+ );
第六步:移除前面在 src/App.css 里全量添加的 @import ‘~antd/dist/antd.css’; 样式代码,并且按下面的格式引入模块。
- import Button from 'antd/es/button';
+ import { Button } from 'antd';
第七步:重启
npm start
第八步:安装自定义主题
第九步:修改配置
- const { override, fixBabelImports } = require('customize-cra');
+ const { override, fixBabelImports, addLessLoader } = require('customize-cra');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
- style: 'css',
+ style: true,
}),
+ addLessLoader({
+ javascriptEnabled: true,
+ modifyVars: { '@primary-color': '#1DA57A' },
+ }),
);
注:每次修改配置文件,想要看到修改的效果都要对项目进行重启。