react 使用antd 按需加載

使用 react-app-rewired

1. 安裝react-app-rewired:

因爲新的 react-app-rewired@2.x 版本的關係,你還須要安裝 customize-cracss

yarn add react-app-rewired customize-cra // npm install react-app-rewired customize-cra

2. 修改package.json:

/* package.json 的配置須要作以下修改*/
"scripts": { -   "start": "react-scripts start", +   "start": "react-app-rewired start", -   "build": "react-scripts build", +   "build": "react-app-rewired build", -   "test": "react-scripts test", +   "test": "react-app-rewired test", }

使用 babel-plugin-import#

babel-plugin-import 是一個用於按需加載組件代碼和樣式的 babel 插件(原理),如今咱們嘗試安裝它並修改 config-overrides.js 文件。react

yarn add babel-plugin-import // npm install babel-plugin-import

 

3. 而後在項目的根目錄下建立一個 config-overrides.js 用於修改默認配置:

const { override, fixBabelImports } = require('customize-cra');
module.exports = override( fixBabelImports('import', { libraryName: 'antd', libraryDirectory: 'es', style: 'css', }), );

4. 使用組件:

import { Button } from 'antd';

 最後重啓 yarn start 訪問頁面,antd 組件的 js 和 css 代碼都會按需加載,你在控制檯也不會看到這樣的警告信息。關於按需加載的原理和其餘方式能夠閱讀這裏git

 官網地址:antd高級配置
github

相關文章
相關標籤/搜索