Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize SVG images #189

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 52 additions & 4 deletions example/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import ExportedImageLegacy from "../src/legacy/ExportedImage";
// import ExportedImageLegacy from "next-image-export-optimizer/legacy/ExportedImage";
// import ExportedImage from "next-image-export-optimizer";
import ExportedImage from "../src/ExportedImage";
import vercelLogo from "../public/vercel.svg";

import styles from "../styles/Home.module.css";
import testPictureStatic from "../public/chris-zhang-Jq8-3Bmh1pQ-unsplash_static.jpg";
Expand Down Expand Up @@ -210,13 +211,60 @@ export default function Home() {
basePath={basePath}
/>
</div>
{/* <ExportedImage
src="vercel.svg"
layout="fixed"
<ExportedImage
src="images/vercel.svg"
width={300}
height={100}
id="test_image_svg"
alt="VercelLogo"
/> */}
style={{ objectFit: "contain" }}
basePath={basePath}
/>
<ExportedImage
src={vercelLogo}
width={300}
height={100}
alt="VercelLogo"
style={{ objectFit: "contain" }}
basePath={basePath}
/>
<ExportedImage
unoptimized
id="test_image_unoptimized_svg"
src={vercelLogo}
width={300}
height={100}
alt="VercelLogo-unoptimized"
basePath={basePath}
/>
<div
style={{
position: "relative",
width: "100%",
height: "200px",
marginBottom: "3rem",
}}
>
<ExportedImage
src="https://reactapp.dev/nextjs.svg"
id="test_image_svg_remote"
fill
sizes="100vw"
alt="NextjsLogo"
style={{ objectFit: "contain" }}
basePath={basePath}
/>
</div>
<ExportedImage
unoptimized
src="https://reactapp.dev/nextjs.svg"
id="test_image_unoptimized_svg_remote"
width={300}
height={100}
alt="NextjsLogo"
style={{ objectFit: "contain" }}
basePath={basePath}
/>
</main>
</div>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@
"subfolder/ollie-barker-jones-K52HVSPVvKI-unsplash.jpg": "eCN-BKBwsstx+QGPEOXBodpbU1DUWgpf1DhnuXeoG8w=",
"subfolder/subfolder2/ollie-barker-jones-K52HVSPVvKI-unsplash.jpg": "AWW05lFZl-Qt-8gAeuDu3bnMm9m6lyTUH80yXpit0Og=",
"/transparentImage.png": "XH3+oYb10y7DOx5iqAbzi64ChyebfrxLgJNJolxjpPw=",
"/vercel.svg": "uHBQYU7ivU446A23G-w9S1uTnW6fa5zBPO0CPLFtOZw=",
"/animated.c00e0188.png": "1u18UQP7SYClRgh+v8TnzU82uY96MSKW3bxNat8HYOo=",
"/chris-zhang-Jq8-3Bmh1pQ-unsplash_small.0fa13b23.jpg": "w8j9FhKoGEyo52uc8zEMt7XCeMUZsGCQjEjnWzkams4=",
"/chris-zhang-Jq8-3Bmh1pQ-unsplash_static.921260e0.jpg": "F4KuoW3LZSTHxrqqDmnFlIcTPSHwtJTKuB2djCCjEnw=",
"/chris-zhang-Jq8-3Bmh1pQ-unsplash_static_asset.921260e0.jpg": "TKroa8LFPMSjLnRq67yFY71qpejsNlpVOV7TkeASSGA=",
"/reactapp.dev_images_nextImageExportOptimizer_christopher-gower-m_HRfLhgABo-unsplash-opt-2048.WEBP": "YtPJvMpqxVbOf++q4Q3h-aYZjThU0rfwOPjZYOtvefg="
"/vercel.1be6ab75.svg": "Q4YZswLklKEkYQU7cv14dsGdoMhqNLL-+Jrf-8wLDzg=",
"/reactapp.dev_images_nextImageExportOptimizer_christopher-gower-m_HRfLhgABo-unsplash-opt-2048.WEBP": "YtPJvMpqxVbOf++q4Q3h-aYZjThU0rfwOPjZYOtvefg=",
"/reactapp.dev_nextjs.svg": "BxmC8w9UBrcnK9wKWpUxw0KmLw8CijHhUCOLcdsYZhI="
}
4 changes: 4 additions & 0 deletions example/public/images/vercel.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions example/remoteOptimizedImages.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
module.exports = [
"https://reactapp.dev/images/nextImageExportOptimizer/christopher-gower-m_HRfLhgABo-unsplash-opt-2048.WEBP",
"https://reactapp.dev/nextjs.svg",
// 'https://example.com/image1.jpg',
// 'https://example.com/image2.jpg',
// 'https://example.com/image3.jpg',
Expand Down
26 changes: 16 additions & 10 deletions example/src/ExportedImage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const generateImageURL = (
: true;

if (
!["JPG", "JPEG", "WEBP", "PNG", "AVIF", "GIF"].includes(
!["JPG", "JPEG", "WEBP", "PNG", "AVIF", "GIF", "SVG"].includes(
extension.toUpperCase()
)
) {
Expand All @@ -47,9 +47,11 @@ const generateImageURL = (

if (
useWebp &&
["JPG", "JPEG", "PNG", "GIF"].includes(extension.toUpperCase())
["JPG", "JPEG", "PNG", "GIF", "SVG"].includes(extension.toUpperCase())
) {
processedExtension = "WEBP";
} else if (extension.toUpperCase() === "SVG") {
processedExtension = "PNG";
}

let correctedPath = path;
Expand Down Expand Up @@ -236,17 +238,12 @@ const ExportedImage = forwardRef<HTMLImageElement | null, ExportedImageProps>(
return generateImageURL(_src, 10, basePath);
}, [blurDataURL, src, unoptimized, basePath]);

// check if the src is a SVG image -> then we should not use the blurDataURL and use unoptimized
const isSVG =
typeof src === "object" ? src.src.endsWith(".svg") : src.endsWith(".svg");

const [blurComplete, setBlurComplete] = useState(false);

// Currently, we have to handle the blurDataURL ourselves as the new Image component
// is expecting a base64 encoded string, but the generated blurDataURL is a normal URL
const blurStyle =
placeholder === "blur" &&
!isSVG &&
automaticallyCalculatedBlurDataURL &&
automaticallyCalculatedBlurDataURL.startsWith("/") &&
!blurComplete
Expand All @@ -260,10 +257,20 @@ const ExportedImage = forwardRef<HTMLImageElement | null, ExportedImageProps>(
const isStaticImage = typeof src === "object";

let _src = isStaticImage ? src.src : src;
if (basePath && !isStaticImage && _src.startsWith("/")) {
if (
basePath &&
!isStaticImage &&
_src.startsWith("/") &&
!_src.startsWith("http")
) {
_src = basePath + _src;
}
if (basePath && !isStaticImage && !_src.startsWith("/")) {
if (
basePath &&
!isStaticImage &&
!_src.startsWith("/") &&
!_src.startsWith("http")
) {
_src = basePath + "/" + _src;
}

Expand All @@ -285,7 +292,6 @@ const ExportedImage = forwardRef<HTMLImageElement | null, ExportedImageProps>(
})}
{...(unoptimized && { unoptimized })}
{...(priority && { priority })}
{...(isSVG && { unoptimized: true })}
style={{ ...style, ...blurStyle }}
loader={
imageError || unoptimized === true
Expand Down
82 changes: 81 additions & 1 deletion example/test/e2e/imageSizeTest.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,65 @@ const correctSrcAnimatedGIFImage = {
imagesWebP ? "WEBP" : "GIF"
}`,
};

const correctSrcSVGImage = {
640: `http://localhost:8080${basePath}/images/nextImageExportOptimizer/vercel-opt-384.${
imagesWebP ? "WEBP" : "PNG"
}`,
750: `http://localhost:8080${basePath}/images/nextImageExportOptimizer/vercel-opt-384.${
imagesWebP ? "WEBP" : "PNG"
}`,
777: `http://localhost:8080${basePath}/images/nextImageExportOptimizer/vercel-opt-384.${
imagesWebP ? "WEBP" : "PNG"
}`,
828: `http://localhost:8080${basePath}/images/nextImageExportOptimizer/vercel-opt-384.${
imagesWebP ? "WEBP" : "PNG"
}`,
1080: `http://localhost:8080${basePath}/images/nextImageExportOptimizer/vercel-opt-384.${
imagesWebP ? "WEBP" : "PNG"
}`,
1200: `http://localhost:8080${basePath}/images/nextImageExportOptimizer/vercel-opt-384.${
imagesWebP ? "WEBP" : "PNG"
}`,
1920: `http://localhost:8080${basePath}/images/nextImageExportOptimizer/vercel-opt-384.${
imagesWebP ? "WEBP" : "PNG"
}`,
2048: `http://localhost:8080${basePath}/images/nextImageExportOptimizer/vercel-opt-384.${
imagesWebP ? "WEBP" : "PNG"
}`,
3840: `http://localhost:8080${basePath}/images/nextImageExportOptimizer/vercel-opt-384.${
imagesWebP ? "WEBP" : "PNG"
}`,
};
const correctSrcSVGImageRemote = {
640: `http://localhost:8080${basePath}/nextImageExportOptimizer/reactapp.dev_nextjs-opt-640.${
imagesWebP ? "WEBP" : "PNG"
}`,
750: `http://localhost:8080${basePath}/nextImageExportOptimizer/reactapp.dev_nextjs-opt-750.${
imagesWebP ? "WEBP" : "PNG"
}`,
777: `http://localhost:8080${basePath}/nextImageExportOptimizer/reactapp.dev_nextjs-opt-777.${
imagesWebP ? "WEBP" : "PNG"
}`,
828: `http://localhost:8080${basePath}/nextImageExportOptimizer/reactapp.dev_nextjs-opt-828.${
imagesWebP ? "WEBP" : "PNG"
}`,
1080: `http://localhost:8080${basePath}/nextImageExportOptimizer/reactapp.dev_nextjs-opt-1080.${
imagesWebP ? "WEBP" : "PNG"
}`,
1200: `http://localhost:8080${basePath}/nextImageExportOptimizer/reactapp.dev_nextjs-opt-1200.${
imagesWebP ? "WEBP" : "PNG"
}`,
1920: `http://localhost:8080${basePath}/nextImageExportOptimizer/reactapp.dev_nextjs-opt-1920.${
imagesWebP ? "WEBP" : "PNG"
}`,
2048: `http://localhost:8080${basePath}/nextImageExportOptimizer/reactapp.dev_nextjs-opt-2048.${
imagesWebP ? "WEBP" : "PNG"
}`,
3840: `http://localhost:8080${basePath}/nextImageExportOptimizer/reactapp.dev_nextjs-opt-3840.${
imagesWebP ? "WEBP" : "PNG"
}`,
};
function generateSrcset(widths, correctSrc) {
const baseURL = "http://localhost:8080";
return widths
Expand Down Expand Up @@ -299,7 +358,26 @@ for (let index = 0; index < widths.length; index++) {

// check the number of images on the page
const images = await page.$$("img");
expect(images.length).toBe(10);
expect(images.length).toBe(15);

// check the SVG images
const imgSVG = await page.locator("#test_image_svg");
await imgSVG.click();

const imageSVG = await getImageById(page, "test_image_svg");

expect(imageSVG.currentSrc).toBe(correctSrcSVGImage[width.toString()]);
expect(imageSVG.naturalWidth).toBe(384);

const imgSVG_remote = await page.locator("#test_image_svg_remote");
await imgSVG_remote.click();

const imageSVG_remote = await getImageById(page, "test_image_svg_remote");

expect(imageSVG_remote.currentSrc).toBe(
correctSrcSVGImageRemote[width.toString()]
);
expect(imageSVG_remote.naturalWidth).toBe(width);
});
test("should check the image size for the appdir", async ({ page }) => {
await page.goto(`${basePath}/appdir`, {
Expand Down Expand Up @@ -478,6 +556,7 @@ for (let index = 0; index < widths.length; index++) {
await img.click();

const image = await getImageById(page, "test_image_static_fixed");
await expect(image).toHaveScreenshot();
expect(image.currentSrc).toBe(
`http://localhost:8080${basePath}/nextImageExportOptimizer/chris-zhang-Jq8-3Bmh1pQ-unsplash_static.921260e0-opt-384.${
imagesWebP ? "WEBP" : "JPG"
Expand All @@ -489,6 +568,7 @@ for (let index = 0; index < widths.length; index++) {
page,
"test_image_static_fixed_future"
);
await expect(image_future).toHaveScreenshot();
expect(image_future.currentSrc).toBe(
`http://localhost:8080${basePath}/nextImageExportOptimizer/chris-zhang-Jq8-3Bmh1pQ-unsplash_static.921260e0-opt-384.${
imagesWebP ? "WEBP" : "JPG"
Expand Down
19 changes: 19 additions & 0 deletions example/test/e2e/unoptimizedTest.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,24 @@ test.describe(`Test unoptimized image prop`, () => {
expect(image_legacy.currentSrc).toBe(
`http://localhost:8080${basePath}/images/chris-zhang-Jq8-3Bmh1pQ-unsplash.jpg`
);

const svg = await page.locator("#test_image_unoptimized_svg");
await svg.click();

const svg_image = await getImageById(page, "test_image_unoptimized_svg");

expect(svg_image.currentSrc).toBe(
`http://localhost:8080${basePath}/_next/static/media/vercel.1be6ab75.svg`
);

const svg_remote = await page.locator("#test_image_unoptimized_svg_remote");
await svg_remote.click();

const svg_image_remote = await getImageById(
page,
"test_image_unoptimized_svg_remote"
);
// TODO: Could be improved by first using a local copy of this remote image
expect(svg_image_remote.currentSrc).toBe(`https://reactapp.dev/nextjs.svg`);
});
});
1 change: 1 addition & 0 deletions playwright-basePath.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ const config = {
use: {
baseURL: "http://localhost:8080/",
},
retries: 2,
testDir: "example/test/e2e",
projects: [
{
Expand Down
1 change: 1 addition & 0 deletions playwright.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const config = {
use: {
baseURL: "http://localhost:8080/",
},
retries: 2,
testDir: "example/test/e2e",
projects: [
{
Expand Down
Loading
Loading