笔记(2019.6.18)
使用antd(在create-react-app中使用)
1.安装:npm install antd --save
2.在css文件中引入antd的css:@import '~antd/dist/antd.css';
就像使用Bootstrap一样,当我们需要哪个组件时,我们就可以引入哪个组件:
import { Button } from 'antd';
...
<Button type="primary">这是antd的按钮</Button>
...
按需加载Antd的css
-
引入 react-app-rewired 并修改 package.json 里的启动配置。由于新的 react-app-rewired@2.x 版本的关系,你还需要安装 customize-cra。
npm install react-app-rewired customize-cra
-
修改package.json: 修改react-scripts为react-app-rewired
-
然后在项目根目录创建一个 config-overrides.js 用于修改默认配置。
module.exports = function override(config, env) {
// do stuff with the webpack config...
return config;
};
- 安装babel-plugin-import babel-plugin-import是一个用于按需加载组件代码和样式的babel插件
npm install babel-plugin-import --save
修改 config-overrides.js 文件。
const { override, fixBabelImports } = require('customize-cra');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: 'css',
}),
);
- 然后移除前面在 src/App.css 里全量添加的 @import ‘~antd/dist/antd.css’; 样式代码,并且按下面的格式引入模块。
// src/App.js
import React, { Component } from 'react';
- import Button from 'antd/lib/button';
+ import { Button } from 'antd';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<Button type="primary">Button</Button>
</div>
);
}
}
export default App;