0
点赞
收藏
分享

微信扫一扫

React配置antd组件按需加载


​​antd文档​​

yarn add antd -s

完整引入

在​​App.css​​中引入

@import '~antd/dist/antd.css';

在组件中引入

import { Button } from 'antd';
render() {
return (
<Button type="primary">Button</Button>
)
}

如果需要自定义主题颜色
安装​​​@craco/craco​​​可以无需暴露​​webpack​​进行配置覆盖

yarn add @craco/craco

​package.json​​更改

"scripts": {
- "start": "react-scripts start",
- "build": "react-scripts build",
- "test": "react-scripts test",
+ "start": "craco start",
+ "build": "craco build",
+ "test": "craco test",
}

安装​​less​

yarn add craco-less

首先把 ​​src/App.css​​​ 文件修改为 ​​src/App.less​​,然后修改样式引用为 less 文件。

​src/App.js​

- import './App.css';
+ import './App.less';

​src/App.less​

- @import '~antd/dist/antd.css';
+ @import '~antd/dist/antd.less';

在根目录新增​​craco.config.js​​​如​​src​​同级

const CracoLessPlugin = require('craco-less');

module.exports = {
plugins: [
{
plugin: CracoLessPlugin,
options: {
lessLoaderOptions: {
lessOptions: {
modifyVars: { '@primary-color': '#1DA57A' },//主题色
javascriptEnabled: true,
},
},
},
},
],
};

按需引入

npm install babel-plugin-import -s

删除​​App.less​​​引入的​​antd.less​​​​craco.config.js​​完整代码

const CracoLessPlugin = require('craco-less');
const path = require("path");
module.exports = {
babel: {
plugins: [
[
"import",
{
"libraryName": "antd",
"libraryDirectory": "es",
"style": true// true 针对less
}
]
]
},
plugins: [
{
plugin: CracoLessPlugin,
options: {
lessLoaderOptions: {
lessOptions: {
modifyVars: { '@primary-color': '#1DA57A' }, //主题色
javascriptEnabled: true,
},
},
},
},
],
//配置src路径
webpack: {
alias: {
"@": path.resolve("src"),
},
},
};


举报

相关推荐

0 条评论