具體參考微信小程序文檔基礎能力 / 分包加載 / 分包異步化
一、分包頁面組件配置
在 UniApp 的pages.json
中,為分包頁面(或主包如 tabbar 頁面)配置異步組件時,需同時設置usingComponents
和componentPlaceholder
:
{"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}`)
})