diff --git a/.changeset/polite-rice-burn.md b/.changeset/polite-rice-burn.md new file mode 100644 index 000000000000..7e9fb0a24a51 --- /dev/null +++ b/.changeset/polite-rice-burn.md @@ -0,0 +1,5 @@ +--- +"@sveltejs/enhanced-img": patch +--- + +fix: throw an error if image cannot be resolved diff --git a/packages/enhanced-img/src/index.js b/packages/enhanced-img/src/index.js index 48347ee6ae97..a33500743dbd 100644 --- a/packages/enhanced-img/src/index.js +++ b/packages/enhanced-img/src/index.js @@ -25,12 +25,15 @@ function image_plugin(imagetools_plugin) { /** * @type {{ * plugin_context: import('vite').Rollup.PluginContext + * vite_config: import('vite').ResolvedConfig * imagetools_plugin: import('vite').Plugin * }} */ 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 }; const preprocessor = image(opts); @@ -40,6 +43,9 @@ function image_plugin(imagetools_plugin) { api: { sveltePreprocess: preprocessor }, + configResolved(config) { + opts.vite_config = config; + }, buildStart() { opts.plugin_context = this; } diff --git a/packages/enhanced-img/src/preprocessor.js b/packages/enhanced-img/src/preprocessor.js index e67adfe8b5bb..0d5d0585ef6a 100644 --- a/packages/enhanced-img/src/preprocessor.js +++ b/packages/enhanced-img/src/preprocessor.js @@ -1,3 +1,6 @@ +import { existsSync } from 'node:fs'; +import * as path from 'node:path'; + import MagicString from 'magic-string'; import { asyncWalk } from 'estree-walker'; import { parse } from 'svelte-parse-markup'; @@ -10,6 +13,7 @@ const OPTIMIZABLE = /^[^?]+\.(avif|heif|gif|jpeg|jpg|png|tiff|webp)(\?.*)?$/; /** * @param {{ * plugin_context: import('vite').Rollup.PluginContext + * vite_config: import('vite').ResolvedConfig * imagetools_plugin: import('vite').Plugin * }} opts * @returns {import('svelte/types/compiler/preprocess').PreprocessorGroup} @@ -72,7 +76,15 @@ export function image(opts) { // need any logic blocks image = await resolve(opts, url, filename); if (!image) { - return; + const file_path = url.substring(0, url.indexOf('?')); + if (existsSync(path.resolve(opts.vite_config.publicDir, file_path))) { + throw new Error( + `Could not locate ${file_path}. Please move it to be located relative to the page in the routes directory or reference it beginning with /static/. See https://vitejs.dev/guide/assets for more details on referencing assets.` + ); + } + throw new Error( + `Could not locate ${file_path}. See https://vitejs.dev/guide/assets for more details on referencing assets.` + ); } images.set(url, image); }