组件按需打包(ant-design)
有的组件有自己的css样式和js特效,那么原来的做法是按照一键导入,需要import 一个总的css包或js包,但这样有点浪费资源。所以可以进行如下配置,实现自动用哪个组件按需要导入相应的css或js包
1、下载依赖包
yarn add antd
yarn add @craco/craco
yarn add craco-less
'请注意':
下面这个依赖包在2.0版本后已经废弃
yarn add react-app-rewired customize-cra babel-plugin-import
若非想要安装这个依赖包,只能是降低自己的 react-app-rewired 版本,或者配置想要的loader(不建议这样做)
// 从 2.0版本开始 react-app-rewired 很多东西被废弃了,The “injectBabelPlugin” helper has been deprecated as of v2.0,这里采用官方推荐的craco
2、修改默认配置(package.json文件)
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test"
}
3、在项目根目录创建文件(config-overrides.js文件)
const CracoLessPlugin = require('craco-less');
module.exports = {
plugins: [
{
plugin: CracoLessPlugin,
options: {
lessLoaderOptions: {
lessOptions: {
modifyVars: { '@primary-color': '#1DA57A' },
javascriptEnabled: true,
},
},
},
},
],
};
4、在src文件夹下创建App.less文件
@import '~antd/dist/antd.less';
5、使用相应App.jsx 组件(如按钮)
import React, { Component } from 'react'
import { Button } from 'antd';
// 导入配置好的less文件
import './App.less';
// 这样就不用导入这个CSS总文件
//import 'antd/dist/antd.css';
export default class App extends Component {
state = {
loadings: [],
};
enterLoading = index => {
this.setState(({ loadings }) => {
const newLoadings = [...loadings];
newLoadings[index] = true;
return {
loadings: newLoadings,
};
});
setTimeout(() => {
this.setState(({ loadings }) => {
const newLoadings = [...loadings];
newLoadings[index] = false;
return {
loadings: newLoadings,
};
});
}, 6000);
};
render() {
const { loadings } = this.state;
return (
<>
<Button type="primary" loading={loadings[0]} onClick={() => this.enterLoading(0)}>
Click me!
</Button>
</>
);
}
}
另外一种方法
yarn add babel-plugin-import
yarn add react-app-rewired customize-cra
yarn add less
yarn add --dev less-loader
修改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 用于修改默认配置。
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': '#119579'}
}
}),
);