解决小程序主包过大问题
354字约1分钟
2025-03-29
小程序对打包有限制,主包大小限制在 2M 以下,所以就得对图片静态文件进行剥离打包,以减小主包大小。
- 在
Vue2
中配置vue.config.js
文件,对webpack
进行配置:
module.exports = {
chainWebpack: config => {
const uniPlatform = process.env.UNI_PLATFORM;
const isMpWeixin = process.env.UNI_PLATFORM === 'mp-weixin';
const isDev = process.env.NODE_ENV === 'development';
console.log('uniPlatform', uniPlatform)
console.log('isMpWeixin', isMpWeixin)
// 转换本地资源到服务器
config.module
.rule('vue')
.use('vue-loader')
.end()
// .use('customLoader')
// .loader(path.resolve(__dirname,'./customLoader.js'))
// 如果是微信环境,就对打包进行优化,添加自定义加载器,将本地图片转换为在图片地址
.when(isMpWeixin, rule => {
rule
.use('customLoader')
.loader(path.resolve(__dirname, './customLoader.js'))
.end();
});
},
}
提示
配置了 customLoader
对本地地址的文件转换为在线地址。当然,需要对 /static/images
文件夹整个上传到服务器
customLoader.js
文件,对图片进行转换:
// uni-app自定义本地图片转线上
// 使用时需要将本地图片上传到服务器下
// 使用示例
// <image class="img" src="@/static/images/pages/hongtu/zeroCarbon/head.png"></image>
// <image src="/static/images/xxx/xxx.png" />
module.exports = function (source) {
// let regex = /@\/static\/images\/(.*?)/;
// return source.replace(regex, (match, p1) => {
// return 'https://imgupload.water7fire.com/hpj/images/' + p1;
// });
// let regex = /^@\/static\/images\//;
// let regex = /\/static\/images\/(.*?)/g;
let regex = /\/static\/images\/(.*?)/g;
return source.replace(regex, 'https://imgupload.water7fire.com/villagesage/images/');
};
对本地图片进行转换,需要将图片上传到服务器下,然后替换成线上地址。