[拆弹时刻]分包大作战,主包调用分包资源问题和若干报错处理
发布于 3 年前 作者 fhu 4239 次浏览 来自 分享

由于一个项目主包要爆了,但是项目的地址二维码已经出去,不能修改,所以必须将一些JS库移到分包中,在这过程中踩了不少坑。

一些错误提示误导性很强,所以我将遇到的都一一罗列出来。

1、显示component组件引入错误,其实是配置问题

错误提示:VM7771 WAService.js:2 Component is not found in path “packageA/ec-canvas/ec-canvas” (using by “pages/smallTools/token”)(env: Windows,mp,1.05.2109262; lib: 2.14.1)

解决方法:
"usingComponents": {
    "ec-canvas": "../../packageA/ec-canvas/ec-canvas",
    "mp-msg": "weui-miniprogram/msg/msg"
},
    "componentPlaceholder": {
    "ec-canvas":"view"
}

JSON配置中没有写:<code>componentPlaceholder</code>,这种常常出现在Components引用时候,因为调用异步,所以需要占位!

2、because they are in diffrent subPackages错误提示

这种错误,一般有两种可能性。

(1)引用路径错误,不支持import直接引用

Error: should not require …/…/packageA/ec-canvas/echarts in pages/smallTools/token.js without a callback,
because they are in diffrent subPackages

//比如:
import * as echarts from '../../packageA/ec-canvas/echarts';

(2)基础库版本太低,比如2.17.3版本以上

VM10490 WAService.js:2 Please do not register multiple Pages in packageA/smallTools/token.js(env: Windows,mp,1.05.2109262; lib: 2.14.1)

let echarts;
require.async('../../packageA/ec-canvas/echarts.js').then(pkg => {
    echarts = pkg;
    console.log(pkg);
})

出现不支持文档中的 <code> require.async </code>,主要原因是__基础库版本过低__。

3、主包/分包A调用其他分包B的资源,必须写在function中

VM10490 WAService.js:2 Please do not register multiple Pages in packageA/smallTools/token.js(env: Windows,mp,1.05.2109262; lib: 2.14.1)

一般可能是引入方法没有写在function中,而直接头部引用

//错误位置
require('../subPackageB/utils.js', utils => {
  console.log(utils.whoami) // Wechat MiniProgram
})
page({
    onLoad(){
        //正确位置
    }
})

4、主包引用分包JS正确的写法(示例)

官方的几个方法都可以,但要注意一些细节,这里展示一个echart图表的实战demo。

//配置JSON:
{
  "navigationBarBackgroundColor": "#1757c4",
  "navigationBarTextStyle": "white",
  "enablePullDownRefresh": true,
  "usingComponents": {
    "ec-canvas": "../../packageA/ec-canvas/ec-canvas",
    "mp-msg": "weui-miniprogram/msg/msg"
  },
  //这个一定要写
  "componentPlaceholder": {
    "ec-canvas":"view"
  }
};

//JS:
let echarts;
page({
    async onLoad(){
        //注意:要写在方法里面
        require('../../packageA/ec-canvas/echarts.js', pkg => {
            echarts = pkg;
        });
        //同步方法
        require.async('../commonPackage/index.js').then(pkg => {
            echarts = pkg; // 'common'
        })
    }
})

单个JS的引用注意点比较多,其他component直接调用即可。

官方文档地址:
https://developers.weixin.qq.com/miniprogram/dev/framework/subpackages/basic.html

(和你一样,我用的时候,压根没一个个字仔细看哈~)

如有疑问请留言~

觉得有用,请点个赞哦,让我继续分享更有动力~

1 回复

好的已读

点个[ 赞同 ],英雄所见略同

回到顶部