【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 中添加页面级别的配置,如果需要在某个组件或者页面中配置,可以使用 插件,支持 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✨ 鼓励一下。

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

相关推荐
绝世唐门三哥1 天前
OpenClaw 安装 + 手动配置 DeepSeek 模型(2026.4.5 版)
前端·oepn claw
来一颗砂糖橘1 天前
吃透 ES6 扩展运算符(...):从表面语法到底层逻辑,避开所有坑
前端·javascript·es6·扩展运算符·前端进阶
前端小D1 天前
JS模块化
开发语言·前端·javascript
Muen1 天前
iOS开发-适配XCode26、iOS26
前端
卸任1 天前
Electron霸屏功能总结
前端·react.js·electron
fengci.1 天前
ctfshow黑盒测试前半部分
前端
px不是xp1 天前
微信小程序组件化开发最佳实践
微信小程序·小程序·notepad++
曲江涛1 天前
微信小程序 摄像头 授权同页面丝滑调用
微信小程序
喵个咪1 天前
Headless 架构优势:内容与展示解耦,一套 API 打通全端生态
前端·后端·cms
小江的记录本1 天前
【JEECG Boot】 JEECG Boot——数据字典管理 系统性知识体系全解析
java·前端·spring boot·后端·spring·spring cloud·mybatis