Fixes ESM imported assets to be root relative (#6465)

* Fixes ESM imported assets to be root relative

* Add changeset
This commit is contained in:
Matthew Phillips 2023-03-08 15:16:13 -05:00 committed by GitHub
parent 9d48328287
commit 65c07ce1b6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 40 additions and 1 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Fixes ESM imported assets to be root relative

View file

@ -9,6 +9,7 @@ import { normalizePath } from 'vite';
import { AstroPluginOptions, ImageTransform } from '../@types/astro';
import { error } from '../core/logger/core.js';
import { joinPaths, prependForwardSlash } from '../core/path.js';
import { rootRelativePath } from '../core/util.js';
import { VIRTUAL_MODULE_ID, VIRTUAL_SERVICE_ID } from './consts.js';
import { isESMImportedImage } from './internal.js';
import { isLocalService } from './services/service.js';
@ -223,7 +224,7 @@ export default function assets({
url.searchParams.append('origHeight', meta.height.toString());
url.searchParams.append('origFormat', meta.format);
meta.src = url.toString();
meta.src = rootRelativePath(settings.config, url);
}
return `export default ${JSON.stringify(meta)}`;

View file

@ -151,6 +151,16 @@ export function relativeToSrcDir(config: AstroConfig, idOrUrl: URL | string) {
return id.slice(slash(fileURLToPath(config.srcDir)).length);
}
export function rootRelativePath(config: AstroConfig, idOrUrl: URL | string) {
let id: string;
if (typeof idOrUrl !== 'string') {
id = unwrapId(viteID(idOrUrl));
} else {
id = idOrUrl;
}
return prependForwardSlash(id.slice(normalizePath(fileURLToPath(config.root)).length));
}
export function emoji(char: string, fallback: string) {
return process.platform !== 'win32' ? char : fallback;
}

View file

@ -212,6 +212,24 @@ describe('astro:image', () => {
expect($img.attr('src').startsWith('/_image')).to.equal(true);
});
});
describe('regular img tag', () => {
/** @type {ReturnType<import('cheerio')['load']>} */
let $;
before(async () => {
let res = await fixture.fetch('/regular-img');
let html = await res.text();
$ = cheerio.load(html);
});
it('does not have a file url', async () => {
expect($('img').attr('src').startsWith('file://')).to.equal(false);
});
it('includes /src in the path', async () => {
expect($('img').attr('src').startsWith('/src')).to.equal(true);
});
});
});
describe('build ssg', () => {

View file

@ -0,0 +1,5 @@
---
import image from "../assets/penguin2.jpg";
---
<img src={image.src} />