Antd按需加载

562 阅读1分钟

1.创建项目

npx create-react-app antd-demo或者 yarn create react-app antd-demo

cd antd-demo

Antd按需加载

1. antd

yarn add antd

2. react-app-rewired 和 customize-cra

yarn add react-app-rewired@2.0.2-next.0 customize-cra --save-dev

  • 在学习React的时候 通过react脚手架create-react-app创建了项目,但是发现了一个问题 如果没有执行eject命令的话 是没有其他配置文件的 这个时候就需要 用到 customize-cra 和 react-app-rewired插件

react-app-rewired的作用就是在不eject的情况下,覆盖create-react-app的配置

  • 配置react-app-rewired为启动方式: 将package.json中scripts中的react-scripts换为react-app-rewired
"scripts": { 
    "start": "react-app-rewired start", 
    "build": "react-app-rewired build", 
    "test": "react-app-rewired test", 
    "eject": "react-app-rewired eject" 
},
3. 配置antd按需加载
  1. 安装:yarn add babel-plugin-import -D

babel-plugin-import 是一个用于按需加载组件代码和样式的 babel 插件 官网

  1. 配置config-overrides.js 写入:
  • 在项目根目录中添加config-overrides.js文件 写入
const { injectBabelPlugin } = require('react-app-rewired');
// injectBabelPlugin 最新的版本已经弃用用这个版本的 
module.exports = function override(config, env){ 
    config = injectBabelPlugin( 
        [ 
        'import', { 
            libraryName: 'antd', 
            //style: 'css', 
            style: true, // use less for customized theme 
         }, 
        ], 
    config 
  ); 
  return config; 
};
4. 使用

import { Button } from 'antd';

<Button type="primary">Primary Button</Button>