Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/witty-chefs-shave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/enhanced-img': minor
---

feat: use jpg as a fallback format
28 changes: 14 additions & 14 deletions packages/enhanced-img/src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import path from 'node:path';
import process from 'node:process';
import { imagetools } from 'vite-imagetools';
import { image_plugin } from './vite-plugin.js';
Expand All @@ -13,26 +12,27 @@ export function enhancedImages() {
: [];
}

/** @type {Record<string,string>} */
const fallback = {
'.avif': 'png',
'.gif': 'gif',
'.heif': 'jpg',
'.jpeg': 'jpg',
'.jpg': 'jpg',
'.png': 'png',
'.tiff': 'jpg',
'.webp': 'png'
};
/**
* @param {import('sharp').Metadata} meta
* @returns {string}
*/
function fallback_format(meta) {
if (meta.format === 'gif') return 'gif';
if (meta.hasAlpha) return 'png';
return 'jpg';
}

function imagetools_plugin() {
/** @type {Partial<import('vite-imagetools').VitePluginOptions>} */
const imagetools_opts = {
defaultDirectives: async ({ pathname, searchParams: qs }, metadata) => {
if (!qs.has('enhanced')) return new URLSearchParams();

const meta = await metadata();

const img_width = qs.get('imgWidth');
const width = img_width ? parseInt(img_width) : (await metadata()).width;
const width = img_width ? parseInt(img_width) : meta.width;

if (!width) {
console.warn(`Could not determine width of image ${pathname}`);
return new URLSearchParams();
Expand All @@ -41,7 +41,7 @@ function imagetools_plugin() {
const { widths, kind } = get_widths(width, qs.get('imgSizes'));
return new URLSearchParams({
as: 'picture',
format: `avif;webp;${fallback[path.extname(pathname)] ?? 'png'}`,
format: `avif;webp;${fallback_format(meta)}`,
w: widths.join(';'),
...(kind === 'x' && !qs.has('w') && { basePixels: widths[0].toString() })
});
Expand Down
Loading