最近在使用uniapp开发微信小程序,随着项目需求的增加,代码包也越来越大,所以不可避免的要进行分包,特此记录下分包过程。
1、首先,在pages同级目录中,创建分包文件夹如helperPages,如图

其中pages放置页面组件,static内为静态图片文件
在page.json文件中添加
"subPackages": [{
"root": "helperPages", //文件夹名称,pages文件夹同级新建一个就行
"pages": [
{
"path": "页面路径",
"style": {
"navigationBarTitleText": "导航title"
}
}]
}],
"preloadRule": {
"pages/index/index": { // pages/index/index为初次加载页面路径
"network": "all",
"packages": ["helperPages"]
}
}
其次,在对应平台配置下添加分包优化"optimization":{"subPackages":true}
选中manifest.json文件,选择源码视图
以微信小程序为例:

页面中使用静态资源,如图片:
<image class="contact" src="/helperPages/static/image/contact.png"></image>
从主包页面跳转子包页面:
uni.navigateTo({
url: '/helperPages/pages/product/detail'
})
tips:分包后直接引入static静态资源中图片,提示找不到
处理方法:
在终端执行命令npm install copy-webpack-plugin --save-dev
然后在根目录下创建vue.config.js 文件
const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
module.exports = {
configureWebpack: {
plugins: [
new CopyWebpackPlugin([
{
from: path.join(__dirname, '/static'),
to: path.join(__dirname+'/unpackage/', 'dist', process.env.NODE_ENV === 'production' ? 'build' : 'dev', process.env.UNI_PLATFORM, '/')
}
])
]
}
}
网友评论