/**
* 移除 preloadAssets 相关代码的函数
* @param {string} str - 需要处理的代码字符串
* @returns {string} 处理后的代码字符串
*/
function removePreloadAssetsCode(str) {
// 正则:仅固定匹配 shadow-grey.png,其余全动态
const regex =
/setTimeout\(\(\(\)=>\{wx\.preloadAssets\(\{data:\[\{type:"image",src:.+?shadow-grey\.png"\}\]\}\)\}\),[\d.eE]+\)/g;
return str.replace(regex, '');
}
/**
* Vite 插件,用于移除 vendor.js 中的 preloadAssets 代码
* @returns {import('vite').Plugin}
*/
export default function removePreloadAssetsPlugin() {
return {
name: 'remove-preload-assets',
/**
* 在打包完成之后,写入文件之前进行处理,此时代码已经压缩
* @param {import('rollup').OutputBundle} bundle - 打包后的文件对象
* @returns {void}
*/
generateBundle(_, bundle) {
// 遍历所有打包后的文件
for (const fileName in bundle) {
const chunk = bundle[fileName];
// 检查是否为 JavaScript 文件且包含 preloadAssets 代码
if (
chunk.type === 'chunk' &&
chunk.fileName.includes('common/vendor') &&
chunk.code.includes('wx.preloadAssets')
) {
const result = removePreloadAssetsCode(chunk.code);
// 更新 chunk 的代码
chunk.code = result;
}
}
},
};
}