簡體   English   中英

使用地塊 2 優化圖像

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM