按需加载
优点
需要按需引入的同学估计一定对他有所了解,因为他实实在在可以提高性能
示例:
我们的框架默认引入ANTD
如果你在开发环境的控制台看到下面的提示,那么你可能使用了 import { Button } from 'antd';
的写法引入了 antd 下所有的模块,这会影响应用的网络性能。
You are using a whole package of antd, please use https://www.npmjs.com/package/babel-plugin-import to reduce app bundle size.
可以通过以下的写法来按需加载组件。
import Button from 'antd/es/button';
import 'antd/es/button/style'; // 或者 antd/es/button/style/css 加载 css 文件
注意:antd 默认支持基于 ES module 的 tree shaking,对于 js 部分,直接引入
import { Button } from 'antd'
也会有按需加载的效果。
我们的框架使用了 babel-plugin-import 来进行按需加载,加入这个插件后。你可以仍然这么写:
import { Button } from 'antd';
在编译时,我们会默默工作,为他进行按需引入的功能
当然,如果您有其他支持ES module
的库,仍然可按照此方法按需引入
如何按需引入支持ES module
的库
在项目下找到config-overrides.js
参考现有文件增加如下
fixBabelImports('import', {
libraryName: 'your lib', //你所需要的库
libraryDirectory: 'es'
}),
这样就完成了ES按需引入