Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support for Vercel Images in enhanced-img #11979

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all 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
34 changes: 23 additions & 11 deletions packages/enhanced-img/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,38 @@ import { imagetools } from 'vite-imagetools';
import { image } from './preprocessor.js';

/**
* @param {Object} options
* @returns {Promise<import('vite').Plugin[]>}
*/
export async function enhancedImages() {
export async function enhancedImages(options) {
const imagetools_instance = await imagetools_plugin();
return !process.versions.webcontainer
? [image_plugin(imagetools_instance), imagetools_instance]
? [image_plugin(imagetools_instance, options), imagetools_instance]
: [];
}

/**
* Creates the Svelte image plugin which provides the preprocessor.
* @param {import('vite').Plugin} imagetools_plugin
* @param {{vercel_sizes: number[]}} options
* @returns {import('vite').Plugin}
*/
function image_plugin(imagetools_plugin) {
function image_plugin(imagetools_plugin, options) {
/**
* @type {{
* plugin_context: import('vite').Rollup.PluginContext
* vite_config: import('vite').ResolvedConfig
* imagetools_plugin: import('vite').Plugin
* vercel_sizes: number[]
* }}
*/
const opts = {
// @ts-expect-error populated when build starts so we cheat on type
plugin_context: undefined,
// @ts-expect-error populated when build starts so we cheat on type
vite_config: undefined,
imagetools_plugin
imagetools_plugin,
vercel_sizes: options.vercel_sizes
};
const preprocessor = image(opts);

Expand Down Expand Up @@ -73,13 +77,21 @@ async function imagetools_plugin() {
return new URLSearchParams();
}

const { widths, kind } = get_widths(width, qs.get('imgSizes'));
return new URLSearchParams({
as: 'picture',
format: `avif;webp;${fallback[path.extname(pathname)] ?? 'png'}`,
w: widths.join(';'),
...(kind === 'x' && !qs.has('w') && { basePixels: widths[0].toString() })
});
if (qs.get('cdn')) {
return new URLSearchParams({
as: 'picture',
format: `${fallback[path.extname(pathname)] ?? 'png'}`,
w: width.toString()
});
} else {
const { widths, kind } = get_widths(width, qs.get('imgSizes'));
return new URLSearchParams({
as: 'picture',
format: `avif;webp;${fallback[path.extname(pathname)] ?? 'png'}`,
w: widths.join(';'),
...(kind === 'x' && !qs.has('w') && { basePixels: widths[0].toString() })
});
}
},
namedExports: false
};
Expand Down
61 changes: 59 additions & 2 deletions packages/enhanced-img/src/preprocessor.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const OPTIMIZABLE = /^[^?]+\.(avif|heif|gif|jpeg|jpg|png|tiff|webp)(\?.*)?$/;
* plugin_context: import('vite').Rollup.PluginContext
* vite_config: import('vite').ResolvedConfig
* imagetools_plugin: import('vite').Plugin
* vercel_sizes: number[]
* }} opts
* @returns {import('svelte/types/compiler/preprocess').PreprocessorGroup}
*/
Expand Down Expand Up @@ -90,7 +91,13 @@ export function image(opts) {
image = await process(resolved_id, opts);
images.set(resolved_id, image);
}
s.update(node.start, node.end, img_to_picture(content, node, image));
s.update(
node.start,
node.end,
url.includes('cdn=vercel')
? img_to_vercel(content, node, image, opts.vercel_sizes, opts.vite_config.env.DEV)
: img_to_picture(content, node, image)
);
} else {
// e.g. <img src="./foo.svg" /> => <img src={___ASSET___0} />
const name = ASSET_PREFIX + imports.size;
Expand Down Expand Up @@ -175,7 +182,9 @@ async function process(resolved_id, opts) {
throw new Error(`Could not load ${resolved_id}`);
}
const code = typeof module_info === 'string' ? module_info : module_info.code;
return parseObject(code.replace('export default', '').replace(/;$/, '').trim());
return parseObject(
code.replace('export default', '').replace('sources:{},', '').replace(/;$/, '').trim()
);
}

/**
Expand Down Expand Up @@ -293,6 +302,54 @@ function img_to_picture(content, node, image) {
return res;
}

/**
* @param {string} content
* @param {import('svelte/types/compiler/interfaces').TemplateNode} node
* @param {import('vite-imagetools').Picture} image
* @param {number[]} sizes
* @param {boolean} isDev
*/
function img_to_vercel(content, node, image, sizes, isDev) {
/** @type {Array<import('svelte/types/compiler/interfaces').BaseDirective | import('svelte/types/compiler/interfaces').Attribute | import('svelte/types/compiler/interfaces').SpreadAttribute>} attributes */
const attributes = node.attributes;

let res = '';
// Need to handle src differently when using either Vite's renderBuiltUrl or relative base path in Vite.
// See https://github.com/vitejs/vite/blob/b93dfe3e08f56cafe2e549efd80285a12a3dc2f0/packages/vite/src/node/plugins/asset.ts#L132
const src =
image.img.src.startsWith('"+') && image.img.src.endsWith('+"')
? `{"${image.img.src.substring(2, image.img.src.length - 2)}"}` // @TODO: Does this affect us???
: `"${image.img.src}"`;

res += `<img srcset="${srcset_vercel(image.img.src, sizes, 99, isDev)}"
${img_attributes_to_markdown(content, attributes, {
src,
width: image.img.w,
height: image.img.h
})}
${
isDev &&
'title="NOTE(dev mode): The srcset image URLs will be more like /_vercel/image?url=...?w=&q= in production."'
}
/>`;

return res;
}

/**
* @param {number[]} widths
*/
function srcset_vercel(src = '', widths, quality = 100, isDev = false) {
return widths
.slice()
.sort((a, b) => a - b)
.map((width) => {
let url = `/_vercel/image?url=${encodeURIComponent(src)}&w=${width}&q=${quality}`;
return `${isDev ? src : url} ${width}w`;
})
.join(', ');
}

/**
* For images like `<img src={manually_imported} />`
* @param {string} content
Expand Down
2 changes: 1 addition & 1 deletion packages/enhanced-img/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ declare module 'svelte/elements' {
}
}

export function enhancedImages(): Promise<Plugin[]>;
export function enhancedImages(options: { vercel_sizes: number[] }): Promise<Plugin[]>;
2 changes: 1 addition & 1 deletion sites/kit.svelte.dev/src/routes/home/Hero.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

<div class="hero-image-wrapper">
<enhanced:img
src="./svelte-kit-machine.webp?w=1440;1080;768;640"
src="./svelte-kit-machine.webp?cdn=vercel&tint=ffaa22"
sizes="(min-width: 768px) min(100vw, 108rem), 64rem"
class="hero-image"
alt="SvelteKit illustration"
Expand Down
8 changes: 7 additions & 1 deletion sites/kit.svelte.dev/svelte.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,13 @@ import adapter from '@sveltejs/adapter-vercel';
const config = {
kit: {
adapter: adapter({
runtime: 'edge'
runtime: 'edge',
images: {
minimumCacheTTL: 300,
formats: ['image/avif', 'image/webp'],
sizes: [480, 1024, 1920, 2560],
domains: []
}
}),

paths: {
Expand Down
4 changes: 3 additions & 1 deletion sites/kit.svelte.dev/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ const config = {
cssMinify: 'lightningcss'
},

plugins: [enhancedImages(), sveltekit()],
plugins: [enhancedImages({
vercel_sizes: [480, 1024, 1920, 2560]
}), sveltekit()],

ssr: {
noExternal: ['@sveltejs/site-kit']
Expand Down
Loading