Skip to content

Commit

Permalink
Merge pull request #219 from Niels-IO/fixSizesOrdering
Browse files Browse the repository at this point in the history
chore: Refactor image optimization logic to remove duplicate widths a…
  • Loading branch information
Niels-IO committed May 26, 2024
2 parents 2e89d2d + 26ed5e2 commit db79f0c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
12 changes: 7 additions & 5 deletions example/src/ExportedImage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -142,13 +142,15 @@ const optimizedLoader = ({
// if it is a static image, we can use the width of the original image to generate a reduced srcset that returns
// the same image url for widths that are larger than the original image
if (isStaticImage && originalImageWidth && width > originalImageWidth) {
const deviceSizes = process.env.__NEXT_IMAGE_OPTS?.deviceSizes || [
const deviceSizes = (process.env.__NEXT_IMAGE_OPTS?.deviceSizes || [
640, 750, 828, 1080, 1200, 1920, 2048, 3840,
];
const imageSizes = process.env.__NEXT_IMAGE_OPTS?.imageSizes || [
]).map(Number);
const imageSizes = (process.env.__NEXT_IMAGE_OPTS?.imageSizes || [
16, 32, 48, 64, 96, 128, 256, 384,
];
const allSizes = [...deviceSizes, ...imageSizes];
]).map(Number);
let allSizes: number[] = [...deviceSizes, ...imageSizes];
allSizes = allSizes.filter((v, i, a) => a.indexOf(v) === i);
allSizes.sort((a, b) => a - b);

// only use the width if it is smaller or equal to the next size in the allSizes array
let nextLargestSize = null;
Expand Down
11 changes: 10 additions & 1 deletion src/optimizeImages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,14 @@ const nextImageExportOptimizer = async function () {
} remote image${remoteImageURLs.length > 1 ? "s" : ""}.`
);

const widths = [...blurSize, ...imageSizes, ...deviceSizes];
let widths = [...blurSize, ...imageSizes, ...deviceSizes];

// sort the widths in ascending order to make sure the logic works for limiting the number of images
widths.sort((a, b) => a - b);

// remove duplicate widths from the array
widths = widths.filter((item, index) => widths.indexOf(item) === index);


const progressBar = defineProgressBar();
if (allImagesInImageFolder.length > 0) {
Expand Down Expand Up @@ -405,6 +412,7 @@ const nextImageExportOptimizer = async function () {
nextLargestSize = Number(widths[i]);
}
}

if (
isStaticImage &&
nextLargestSize !== -1 &&
Expand Down Expand Up @@ -603,3 +611,4 @@ if (require.main === module) {
nextImageExportOptimizer();
}
module.exports = nextImageExportOptimizer;

0 comments on commit db79f0c

Please sign in to comment.