Skip to content

Commit

Permalink
fix: throw an error if image cannot be resolved (#11346)
Browse files Browse the repository at this point in the history
  • Loading branch information
benmccann authored Dec 19, 2023
1 parent 5551e35 commit 9da6508
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/polite-rice-burn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@sveltejs/enhanced-img": patch
---

fix: throw an error if image cannot be resolved
6 changes: 6 additions & 0 deletions packages/enhanced-img/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -40,6 +43,9 @@ function image_plugin(imagetools_plugin) {
api: {
sveltePreprocess: preprocessor
},
configResolved(config) {
opts.vite_config = config;
},
buildStart() {
opts.plugin_context = this;
}
Expand Down
14 changes: 13 additions & 1 deletion packages/enhanced-img/src/preprocessor.js
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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}
Expand Down Expand Up @@ -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);
}
Expand Down

0 comments on commit 9da6508

Please sign in to comment.