Refactor Image component to improve asset handling and prevent CORS issues

- Enhanced the image loading logic to directly serve imported assets during development, avoiding Astro's on-demand service to prevent 500 errors.
- Implemented fallback mechanisms to ensure original sources are rendered if optimization fails.
- Adjusted the rendering of images to eliminate crossorigin attributes, addressing potential CORS/COEP conflicts for local assets.
This commit is contained in:
2025-10-19 23:11:05 +02:00
parent a767dbb115
commit 2242a33754

View File

@@ -41,6 +41,21 @@ const _image = await findImage(props.src);
let image: ImageType | undefined = undefined;
// In dev/preview, avoid Astro's on-demand /_image service to prevent 500s; serve the imported asset directly
if (import.meta.env.DEV && _image && typeof _image !== 'string') {
image = {
src: _image.src,
attributes: {
width: typeof props.width === 'number' ? props.width : _image.width,
height: typeof props.height === 'number' ? props.height : _image.height,
alt: props.alt || '',
loading: props.loading || 'lazy',
decoding: props.decoding || 'async',
},
} as unknown as ImageType;
}
if (!image) {
if (
typeof _image === 'string' &&
(_image.startsWith('http://') || _image.startsWith('https://')) &&
@@ -50,12 +65,29 @@ if (
} else if (_image) {
image = await getImagesOptimized(_image, props, astroAsseetsOptimizer);
}
}
// Fallback: if optimization produced no output, render the original source directly
if (!image && _image) {
const originalSrc = typeof _image === 'string' ? _image : _image.src;
image = {
src: originalSrc,
attributes: {
alt: props.alt || '',
width: typeof props.width === 'number' ? props.width : undefined,
height: typeof props.height === 'number' ? props.height : undefined,
loading: props.loading || 'lazy',
decoding: props.decoding || 'async',
},
} as unknown as ImageType;
}
---
{
!image ? (
<Fragment />
) : (
<img src={image.src} crossorigin="anonymous" referrerpolicy="no-referrer" {...image.attributes} />
// Render without crossorigin to avoid CORS/COEP conflicts for local assets; keep attributes from optimizer
<img src={image.src} {...image.attributes} />
)
}