【uniapp】小程序体积优化,分包异步化

前言

在小程序端,分包异步化 是一个重要的减小体积的手段,下面会介绍如何在 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 中添加页面级别的配置,如果需要在某个组件或者页面中配置,可以使用 uni-toolkit 插件,支持 vue2vue3

跨分包 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✨ 鼓励一下。

如果你有什么好的想法或者建议,欢迎在 https://github.com/uni-toolkit/uni-toolkit 提 issue 或者 pr

相关推荐
无羡仙31 分钟前
从零构建 Vue 弹窗组件
前端·vue.js
源心锁2 小时前
👋 手搓 gzip 实现的文件分块压缩上传
前端·javascript
源心锁2 小时前
丧心病狂!在浏览器全天候记录用户行为排障
前端·架构
GIS之路2 小时前
GDAL 实现投影转换
前端
烛阴2 小时前
从“无”到“有”:手动实现一个 3D 渲染循环全过程
前端·webgl·three.js
BD_Marathon3 小时前
SpringBoot——辅助功能之切换web服务器
服务器·前端·spring boot
Kagol3 小时前
JavaScript 中的 sort 排序问题
前端·javascript
eason_fan3 小时前
Service Worker 缓存请求:前端性能优化的进阶利器
前端·性能优化
光影少年3 小时前
rn如何和原生进行通信,是单线程还是多线程,通信方式都有哪些
前端·react native·react.js·taro
好大哥呀4 小时前
Java Web的学习路径
java·前端·学习