UniApp 分包异步化配置及组件引用解决方案

发布于:2025-09-11 ⋅ 阅读:(16) ⋅ 点赞:(0)

具体参考微信小程序文档基础能力 / 分包加载 / 分包异步化

一、分包页面组件配置

在 UniApp 的pages.json中,为分包页面(或主包如 tabbar 页面)配置异步组件时,需同时设置usingComponentscomponentPlaceholder

{
  "path": "pages/smart/index",
  "style": {
    "navigationBarTitleText": "智能家居",
    "disableScroll": true,
    "backgroundColor": "#F9FAFB",
    "backgroundColorContent": "#F9FAFB",
    "backgroundColorTop": "#F9FAFB",
    "backgroundColorBottom": "#F9FAFB",
    // 声明需要引入的异步组件
    "usingComponents": {
      "smart-device-detail": "/pages/smart/sub/components/smartDeviceDetail",
      "normal-device-detail": "/pages/smart/sub/components/normalDeviceDetail"
    },
    // 组件未加载完成时的占位组件
    "componentPlaceholder": {
      "smart-device-detail": "view",
      "normal-device-detail": "view"
    }
  }
}

解决组件找不到的问题

直接上述配置可能导致 “组件找不到” 报错,原因是 UniApp 的摇树优化会过滤未在页面中显式引入的组件。

解决方案:在对应的分包页面内手动引入组件

二、跨分包 JS 代码引用

跨分包引用 JS 可直接使用微信小程序的语法,支持两种方式:

// subPackageA/index.js
// 使用回调函数风格的调用
require('../subPackageB/utils.js', utils => {
  console.log(utils.whoami) // Wechat MiniProgram
}, ({mod, errMsg}) => {
  console.error(`path: ${mod}, ${errMsg}`)
})
// 或者使用 Promise 风格的调用
require.async('../commonPackage/index.js').then(pkg => {
  pkg.getPackageName() // 'common'
}).catch(({mod, errMsg}) => {
  console.error(`path: ${mod}, ${errMsg}`)
})


网站公告

今日签到

点亮在社区的每一天
去签到