如何实现组件库按需加载

一)实现方式

  1. 通过安装 babel-plugin-import (推荐)

.babelrc or babel-loader option

{
  "plugins": [
    [
      "import",
      {
        "libraryName": "antd-mobile",
        "style": "css" // style: "css" 加载 css;"true" 加载 less
      }
    ]
  ]
}
  1. 手动引入
import DatePicker from "antd-mobile/lib/date-picket";
import "antd-mobile/lib/date-picker/style/css"
//import "antd-mobile/lib/date-picker/style"    //加载less

二)支持的库

三) 实现原理

配置项:{ "libraryName": "antd", style: "css" }

style参数说明:

import { Button } from 'antd';
ReactDOM.render(<Button>xxxx</Button>);

      ↓ ↓ ↓ ↓ ↓ ↓

var _button = require('antd/lib/button');
require('antd/lib/button/style/css');
ReactDOM.render(<_button>xxxx</_button>);

补充

补充:按需加载方案对比:

  • babel-plugin-import(antd-mobile、antd、vant、element-ui 老版本常用):编译时把 import { Button } from 'antd' 重写为 import Button from 'antd/lib/button',加上 import 'antd/lib/button/style/css'。
  • tree-shaking + ES Module:antd v4+ / antd v5 / React 18 已全面 ESM,只要 package.json 标 "sideEffects": false + bundler 支持 usedExports,即可自动按需引入,无需 babel 插件。
  • 手动精确引入:直接 import Button from 'antd-mobile/lib/button',可读性最好但繁琐。 现代项目推荐方案:使用支持 ESM 的组件库 + 开启 tree-shaking,不再依赖 babel-plugin-import。

来源整理自:我的有道云笔记