jd-opensource / jd-opensource/taro-ui

实现taro-ui组件的按需加载,内详

Open
#1,328 11 comments 4 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
4.7k
Forks
740
PR merge metrics
No merged PRs in 30d

Description

由于使用taro框架一般都会使用taro-ui来提供双线程组件的需求,但是taro-ui在h5端打包的时候,确实使用了dist目录下的全量脚本,从package.json的main就能看出。但是毕竟h5端的需求量还是很大,也有很多团队会使用taro来编写h5端的需求,因此在h5端上进行taro-ui的全量脚本导出会显得那么的“笨拙”。因此需要提供一个“按需加载”的思路,而前端应用层代码依然是从taro-ui命名空间进行使用,以下是我的解决方案,官方可参考是否可在NEXT版本中进行优化。

这个功能解决了什么问题?
解决并提供taro-ui按需加载的问题,同时应用层的代码还是通过taro-ui进行导入导出。

你期望的功能是怎样的?
无需使用接下去的解决方案来解决,最好官方能天然的进行支持。

补充信息
1. 安装 babel-plugin-import 插件:
```javascript
cnpm i babel-plugin-import --save-dev
```

2. 在根目录下的 babel.config.js 中进行如下配置:
```javascript
const tail = require("lodash/tail");
module.exports = {
presets: [
['taro', {
framework: 'react',
ts: true
}]
],
plugins: [
["import", {
libraryName: "taro-ui",
customName: (name, file) => {
const path = tail(name.split('-')).join('/');
return `taro-ui/lib/components/${path}`;
}
}]
]
}
```

3. 应用层的代码依然还是这么引用:
```javascript
import { AtModal, AtModalHeader, AtModalContent, AtModalAction, AtButton } from "taro-ui";
```

虽然在应用层开发者还是可以直接使用 taro-ui/lib 来解决问题,或者设置alias别名,但是alias还需要考虑按需加载 css 路径的问题,这让我一直很困惑,为什么css官方考虑了按需,而最重要的js层则是全量的,因此给出通过工具链的方式解决按需加载的问题,应该也是大多数开发者一直希望支持的,最后给出两张对比图结束!

未配置前:
![image](https://user-images.githubusercontent.com/11752878/115138670-23088e80-a060-11eb-8e53-d68ab6b5aad4.png)

配置后:
![image](https://user-images.githubusercontent.com/11752878/115138691-34519b00-a060-11eb-8499-412daf8d3104.png)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.