From 09ebbc136e6add1f1103d02589edd13a85553ef1 Mon Sep 17 00:00:00 2001 From: Princesseuh <3019731+Princesseuh@users.noreply.github.com> Date: Thu, 11 Jul 2024 16:09:52 +0200 Subject: [PATCH] fix(assets): Don't delete original images if multiple images were generated with the same name and hash --- packages/astro/src/assets/build/generate.ts | 7 +++++++ packages/astro/src/assets/types.ts | 1 + packages/astro/src/assets/vite-plugin-assets.ts | 10 +++++++++- 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/packages/astro/src/assets/build/generate.ts b/packages/astro/src/assets/build/generate.ts index c363a63497..b7711431a3 100644 --- a/packages/astro/src/assets/build/generate.ts +++ b/packages/astro/src/assets/build/generate.ts @@ -115,6 +115,13 @@ export async function generateImagesForPath( transformsAndPath.originalSrcPath && !globalThis.astroAsset.referencedImages?.has(transformsAndPath.originalSrcPath) ) { + // If multiple images imports resulted in the same output file, don't delete the original file as + // we cannot know if the other references to it are used or not. + const creationCount = globalThis.astroAsset.originalAssets?.[basename(originalFilePath)]; + if (creationCount && creationCount > 1) { + return; + } + try { if (transformsAndPath.originalSrcPath) { env.logger.debug( diff --git a/packages/astro/src/assets/types.ts b/packages/astro/src/assets/types.ts index 98f42c045c..e91e543b09 100644 --- a/packages/astro/src/assets/types.ts +++ b/packages/astro/src/assets/types.ts @@ -25,6 +25,7 @@ declare global { | undefined; staticImages?: AssetsGlobalStaticImagesList; referencedImages?: Set; + originalAssets?: Record }; } diff --git a/packages/astro/src/assets/vite-plugin-assets.ts b/packages/astro/src/assets/vite-plugin-assets.ts index eda4b6cfbc..7ba42ff1c4 100644 --- a/packages/astro/src/assets/vite-plugin-assets.ts +++ b/packages/astro/src/assets/vite-plugin-assets.ts @@ -1,4 +1,4 @@ -import { extname } from 'node:path'; +import { basename, extname } from 'node:path'; import MagicString from 'magic-string'; import type * as vite from 'vite'; import { normalizePath } from 'vite'; @@ -99,6 +99,7 @@ export default function assets({ globalThis.astroAsset = { referencedImages: new Set(), + originalAssets: {} }; return [ @@ -173,6 +174,13 @@ export default function assets({ const [full, hash, postfix = ''] = match; const file = this.getFileName(hash); + const fileBasename = basename(file); + + if (globalThis.astroAsset.originalAssets) { + globalThis.astroAsset.originalAssets[fileBasename] ??= 0; + globalThis.astroAsset.originalAssets[fileBasename]++; + } + const fileExtension = extname(file); const pf = getAssetsPrefix(fileExtension, settings.config.build.assetsPrefix); const prefix = pf ? appendForwardSlash(pf) : resolvedConfig.base;