[英]Optimizing images using parcel 2
我想使用 Parcel 2 内置的图像优化器动态优化我的图像。 图像 url 来自 data.js,然后我传递它来渲染它。
当我使用此代码时,它正在工作:
_generateMarkupProjects(project) {
const imageUrl = new URL('../../images/projectOne.webp?width=640', import.meta.url);
return `
<div class="projects__box">
<figure class="projects__img-box">
<picture>
<img
src="${imageUrl}"
sizes="(max-width: 800px) 45vw"
alt="${project.name} Photo"
class="projects__image"
/>
</picture>
<figcaption class="projects__caption">
<button class="projects__maximize-btn" data-id="${project.id}">
<svg class="projects__icon">
<use
xlink:href="${icon}#icon-maximize"
></use>
</svg>
</button>
<div class="projects__caption-content">
<h3 class="projects__caption-title u-mb-xxs">
${project.name}
</h3>
<p class="projects__caption-description u-mb-xxs">
${project.description}
</p>
<div class="projects__language">${project.languages.join(
', '
)}</div>
</div>
</figcaption>
</figure>
</div>
`;
}
但是当我这样做时:parcel 没有优化图像。
const imageUrl = new URL(`${project.image}?width=640`, import.meta.url);
这是我导入项目图像的方式:
//data.js
import projectOne from 'url:../images/projectOne.webp';
不幸的是,我认为这是预期的行为。 Parcel 需要能够确定如何在构建时静态地转换图像(尺寸、质量等)。 仅当它找到对图像位置的引用以及在一个地方指定所需转换的查询参数(例如, const imageUrl = new URL("./image.webp?width=640", import.meta.url);
或import imageUrl from "url:./image.webp?width=640"
看起来您的意图是创建一个 function 接受(未转换的)图像 url 作为参数,然后动态应用width
转换。 为了在构建时正确地执行此操作,Parcel 需要在运行时完全了解您的代码流——例如,哪些未转换的图像 url 将被提供给 function,因此需要转换? 在一个简单的案例中它可能是可知的,但是用一般的方式解决它几乎是不可能的。
所以我认为您需要重构您的代码,以便在您首先引用图像时应用width
变换(例如在data.js
中)。 如果您需要多种图像尺寸,您可以使项目 object 具有多个属性,每个属性对应一个尺寸,例如:
const project1 = {
smallImageUrl: new URL(`../images/projectOne.webp?width=240`, import.meta.url);
bigImageUrl: new URL(`../images/projectOne.webp?width=640`, import.meta.url);
// etc.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.