前言
在小程序端,分包异步化 是一个重要的减小体积的手段,下面会介绍如何在 uniapp 中 分包异步化。
跨分包自定义组件引用
在页面中正常使用: import CustomButton from "@/packageB/components/component1/index.vue";
json
{
"pages": [
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "Index",
"componentPlaceholder": {
"custom-button": "view"
}
}
}
],
"subPackages": [
{
"root": "packageA",
"pages": [
{
"path": "index/index",
"style": {
"navigationBarTitleText": "分包页面",
// 添加配置
"componentPlaceholder": {
"custom-button": "view"
}
}
}
]
},
{
"root": "packageB",
"pages": [
{
"path": "index/index",
}
],
}
]
}
此特性依赖配置 componentPlaceholder,目前 uniapp 仅支持在 pages.json 中添加页面级别的配置,如果需要在某个组件或者页面中配置,可以使用 插件,支持 vue2 和 vue3
跨分包 JS 代码引用
小程序端默认支持跨分包 JS 代码引用,需要写小程序原生支持的语法,不能使用静态引入或者动态引入。示例如下:
sub分包 定义 utils.js 文件
javascript
// sub/utils.js
export function add(a, b) {
return a + b
}
sub分包 正常使用 utils.js 文件
vue
// sub/index.vue
<template>
<view>
{{ count }}
<button @tap="handleClick">add one</button>
</view>
</template>
<script>
import {
add
} from "./utils.js";
export default {
data() {
return {
count: 1
}
},
methods: {
handleClick() {
this.count = add(this.count, 1)
}
}
}
</script>
其他分包使用 sub分包 的 utils.js 文件
vue
// sub2/index.vue
<template>
<view>
{{ count }}
<button @tap="handleClick">add two</button>
</view>
</template>
<script>
export default {
data() {
return {
count: 1
}
},
methods: {
handleClick() {
require('../sub/utils.js', sub_utils => {
this.count = sub_utils.add(this.count, 2);
}, ({
mod,
errMsg
}) => {
console.error(`path: ${mod}, ${errMsg}`)
})
}
}
}
</script>
注意:
- 引用的文件必须存在
- 使用小程序支持的原生语法
结语
如果这个库的插件帮助到了你,可以点个 star✨ 鼓励一下。
如果你有什么好的想法或者建议,欢迎在 github.com/uni-toolkit... 提 issue 或者 pr