react中按需引入ant的样式

创建项目

create-react-app react-ant

安装antd

npm install antd --save

暴露隐藏文件

npm eject
npm add react-app-rewired customize-cra

然后在项目根目录创建一个 config-overrides.js 用于修改默认配置。

接着

npm add babel-plugin-import

babel-plugin-import 是一个用于按需加载组件代码和样式的 babel 插件(原理),现在我们尝试安装它并修改 config-overrides.js 文件。

const {
          
    override, fixBabelImports } = require(customize-cra);

 module.exports = override(
   fixBabelImports(import, {
          
   
     libraryName: antd,
     libraryDirectory: es,
     style: css,
   }),
 );

最后引入组件

import React, {
          
    Component } from react
import {
          
    Button} from "antd";

export default class App extends Component {
          
   
  render() {
          
   
    return (
      <div>
        <Button type="primary" style={
          
   {
          
    marginLeft: 8 }}>
          Primary Button
       </Button>
      </div>
    )
  }
}
经验分享 程序员 微信小程序 职场和发展