react --- > 按需加载组件

mac2025-04-09  10

问题描述

使用 antd库时使用按钮,须导入如下 import Button from 'antd/lib/button' import 'antd/dist/antd.css' 这样会导入全局的样式.

解决方案,配置按需加载

1.安装 react-app-rewired取代 react-scripts, 可以扩展webapack 的配置, 类似vue.config.jsnpm install react-app-rewired@2.0.2-next.0 babel-plugin-import --save/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; } 2.改启动脚本/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.使用按需导入 // import Button from 'antd/lib/button' // import 'antd/dist/antd.css' import { Button } from 'antd'

最新回复(0)