0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2024-12-16 21:46:22 -05:00

fix(assets): Fix image errors when images were used on the client (#9049)

* fix(assets): Fix image errors when images were used on the client

* test: add a test

* chore: changeset
This commit is contained in:
Erika 2023-11-10 14:01:04 +01:00 committed by GitHub
parent bf0286e50c
commit 49b82edb2c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 34 additions and 3 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Fix image errors when images were used on the client

View file

@ -175,7 +175,7 @@ export default function assets({
configResolved(viteConfig) {
resolvedConfig = viteConfig;
},
async load(id) {
async load(id, options) {
// If our import has any query params, we'll let Vite handle it
// See https://github.com/withastro/astro/issues/8333
if (id !== removeQueryString(id)) {
@ -191,8 +191,18 @@ export default function assets({
});
}
return `
export default ${getProxyCode(meta, isServerLikeOutput(settings.config))}`;
// We can only reliably determine if an image is used on the server, as we need to track its usage throughout the entire build.
// Since you cannot use image optimization on the client anyway, it's safe to assume that if the user imported
// an image on the client, it should be present in the final build.
if (options?.ssr) {
return `export default ${getProxyCode(meta, isServerLikeOutput(settings.config))}`;
} else {
if (!globalThis.astroAsset.referencedImages)
globalThis.astroAsset.referencedImages = new Set();
globalThis.astroAsset.referencedImages.add(meta.fsPath);
return `export default ${JSON.stringify(meta)}`;
}
}
},
},

View file

@ -935,6 +935,18 @@ describe('astro:image', () => {
expect(isReusingCache).to.be.true;
});
it('client images are written to build', async () => {
const html = await fixture.readFile('/client/index.html');
const $ = cheerio.load(html);
let $script = $('script');
// Find image
const regex = /src:"([^"]*)/gm;
const imageSrc = regex.exec($script.html())[1];
const data = await fixture.readFile(imageSrc, null);
expect(data).to.be.an.instanceOf(Buffer);
});
describe('custom service in build', () => {
it('uses configured hashes properties', async () => {
await fixture.build();

View file

@ -0,0 +1,2 @@
import light_walrus from "../assets/light_walrus.avif";
console.log(light_walrus);

View file

@ -0,0 +1,2 @@
<script src="../client/client-image.ts"></script>
<div></div>