0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2024-12-30 22:03:56 -05:00

refactor: move relative repath after emitESMImage

This commit is contained in:
Josh Chappelow 2024-08-19 05:50:46 +09:00
parent 245034babb
commit dc105b8d42

View file

@ -310,16 +310,8 @@ async function emitOptimizedImages(
if ((node.type === 'image' || isComponent) && typeof node.attributes.src === 'string') { if ((node.type === 'image' || isComponent) && typeof node.attributes.src === 'string') {
let attributeName = isComponent ? 'src' : '__optimizedSrc'; let attributeName = isComponent ? 'src' : '__optimizedSrc';
if (node.attributes.src.startsWith('./') || node.attributes.src.startsWith('../')) {
node.attributes.src = prependForwardSlash(
path.relative(
ctx.astroConfig.root.pathname,
path.join(path.dirname(ctx.filePath), node.attributes.src),
),
);
}
// If the image isn't an URL or a link to public, try to resolve it. // If the image isn't an URL or a link to public, try to resolve it.
if (shouldOptimizeImage(node.attributes.src, ctx.astroConfig.root.pathname)) { if (shouldOptimizeImage(node.attributes.src)) {
// Attempt to resolve source with Vite. // Attempt to resolve source with Vite.
// This handles relative paths and configured aliases // This handles relative paths and configured aliases
const resolved = await ctx.pluginContext.resolve(node.attributes.src, ctx.filePath); const resolved = await ctx.pluginContext.resolve(node.attributes.src, ctx.filePath);
@ -340,9 +332,17 @@ async function emitOptimizedImages(
if (globalThis.astroAsset.referencedImages) if (globalThis.astroAsset.referencedImages)
globalThis.astroAsset.referencedImages.add(fsPath); globalThis.astroAsset.referencedImages.add(fsPath);
} }
node.attributes[attributeName] = { ...src, fsPath };
node.attributes.src = src.src;
// Repath relative image path for use in Markdoc image component
if (node.attributes.src.startsWith('./') || node.attributes.src.startsWith('../')) {
node.attributes.src = prependForwardSlash(
path.relative(
ctx.astroConfig.root.pathname,
path.join(path.dirname(ctx.filePath), node.attributes.src),
),
);
}
node.attributes[attributeName] = { ...src, fsPath };
} }
} else { } else {
throw new MarkdocError({ throw new MarkdocError({
@ -361,15 +361,9 @@ async function emitOptimizedImages(
} }
} }
function shouldOptimizeImage(src: string, rootPath: string) { function shouldOptimizeImage(src: string) {
// Optimize anything that is NOT external or an absolute path to `public/` // Optimize anything that is NOT external or an absolute path to `public/`
if (isValidUrl(src)) return false; return !isValidUrl(src) && !src.startsWith('/');
const normPath = path.normalize(src);
if (normPath.startsWith(rootPath) || normPath.startsWith('/')) {
return false;
}
return true;
} }
/** /**