taro3打包时图片转base64问题

769 阅读1分钟
  1. 由于tar3 webpack 打包时,会把小于10k的图片文件转化为base64格式。
  2. 然而在地图组件中的Marker的iconPath不支持base64格式,导致真机无法显示。

image.png

const iconPath = require('@/assets/images/map-project.png');

const handleMarkerData = function (projectList) {
  const markersData: MarkerType[] = [];
  projectList.forEach((el, index) => {
    if (el.Longitude > 0 && el.Latitude > 0) {
      markersData.push({
        iconPath,
        id: index,
        longitude: el.Longitude,
        latitude: el.Latitude,
        width: 50,
        height: 50,
      });
    }
  });
  markers.value = markersData;
};
  1. 通过查看文档,可使用mini.imageUrlLoaderOption 配置limit,全部图片不转base64
module.exports = {  
// ...  
mini: {  
// ...  
    imageUrlLoaderOption: {  
        limit: 0,  
    },  
},  
}

但这样也有个弊端 微信小程序里面的css使用的背景图, 不能本地路径显示,需要base64或者远程图片

解决方案

  1. 把这个图片放服务器,使用远程图片链接在iconPath
  2. icon使用相对路径,移动一份文件到dist中
// 业务端使用
const iconPath = '/assets/images/map-project.png';
// config/index.js
// 把不需要转的文件放在public文件夹中
copy: {
patterns: [{ from: 'src/assets/images/public', to: 'dist/assets/images/' }],
options: {},
},

  1. 修改webpack配置,让url-loader的use匹配不到这个图片