React中使用Antd高级配置,按需引入css样式
@import '~antd/dist/antd.css'把组件成功运行起来了,但是在实际开发过程中还有很多问题,实际上加载了全部的 antd 组件的样式(对前端性能是个隐患)。
1、安装antd npm install antd --save
2、安装(react-app-rewired)一个对 create-react-app 进行自定义配置的社区解决方案
yarn add react-app-rewired / cnpm install react-app-rewired --save
3、修改 package.json
react-scripts 需改为react-app-rewired
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test --env=jsdom",
"eject": "react-app-rewired eject"
},
4、在项目根目录创建一个 config-overrides.js 用于修改默认配置
module.exports = function override(config, env) {
// do stuff with the webpack config...
return config;
};
5、安装babel-plugin-import babel-plugin-import是一个用于按需加载组件代码和样式的 babel 插件
yarn add babel-plugin-import
6、修改 config-overrides.js
const { injectBabelPlugin } = require('react-app-rewired');
module.exports = function override(config, env) {
config = injectBabelPlugin(
['import', { libraryName: 'antd', libraryDirectory: 'es', style: 'css' }],
config,
);
return config;
};
7、然后移除前面在 src/App.css 里全量添加的 @import '~antd/dist/antd.css'; 直接引入组件使用就会有对应的css
import { Button } from 'antd';
<Button type="primary">Primary</Button>
8.报错The "injectBabelPlugin" helper has been deprecated as of v2.0. You can use customize-cra plugins in replacement - https://github.com/arackaf/cu...
转载至https://blog.csdn.net/zoepris...
1.首先确保你安装了以下几个包:
yarn add less less-loader
yarn add customize-cra
yarn add react-app-rewired@2.x
2.然后要在根目录下添加个config-overrides.js的文件,内容如下:
const {
override,
fixBabelImports,
addLessLoader,
} = require("customize-cra");
module.exports = override(
fixBabelImports("import", {
libraryName: "antd", libraryDirectory: "es", style: true // change importing css to less
}),
addLessLoader({
javascriptEnabled: true,
modifyVars: { "@primary-color": "#1DA57A" }
})
);
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。