解决 parcel打包图片不显示

206 阅读1分钟

背景

原生 html 开发微信公众号 h5 页面,使用 parcel 进行打包,引入图片文件在本地环境中一切正常,但是部署到测试机器后不能正常显示,不报错,只是显示如下图标:

image.png

原因

有博主说是因为图片虽然是 .png 后缀的,但是格式是 webp 在某些 ios 中无法正常显示。我检查了下,图片格式并不是webp。所以排除了此原因。

然后我运行打包命令,看了一下打包后的文件,我发现在 html 中以 <img src="./img/aaa.png" /> 的形式引入的资源都打包进去了,使用 js 引入的资源没有打包进去。

原因是 parcel 是根据 source 配置的 html 文件进行依赖分析的,所以 js 中的资源没有打包进去。

解决

js 中资源的引入更改为:

const rejectImg = new URL(
    '../img/aaa.png',
    import.meta.url
  );

官网

官网上说:

Parcel will process any files referenced by a URL dependency as it does any other dependency. For example, images will be processed by the image transformer, and you can use query parameters to specify options to resize and convert them. If no transformers are configured for a particular file type, then the file will be copied into the dist directory unmodified. The resulting file names will also include a content hash for long term cacheability in the browser.

翻译是:

Parcel将像处理其他依赖项一样处理URL依赖项引用的任何文件。例如,图像将由图像转换器处理,您可以使用查询参数指定调整大小和转换它们的选项。如果没有为特定文件类型配置转换器,则该文件将不加修改地复制到dist目录。生成的文件名还将包含一个内容散列,用于在浏览器中进行长期缓存。