imagetools
imagetools copied to clipboard
Works in dev, build fails with `Unknown variable dynamic import`
I'm using vite-imagetools
version 4.0.3
with SvelteKit.
This code...
const { default: srcset } = await import(`./${slug}/cover.jpg?width=1344;672;336&srcset`);
...works as expected in dev mode, but build fails with error:
Error: Unknown variable dynamic import: ./article1/cover.jpg?width=1344;672;336&srcset
at file:///Users/arggh/Develop/testapp/.svelte-kit/output/server/entries/pages/index.svelte.js:15:96
at new Promise (<anonymous>)
at __variableDynamicImportRuntime1__ (file:///Users/arggh/Develop/testapp/.svelte-kit/output/server/entries/pages/index.svelte.js:14:14)
...
If I remove the query string from my import statement the build doesn't fail, but obviously any transformations don't take place.
Hey,
we've kind of solved this issue (partly) as follows:
vite.config.js
const directives = {
imagecardPreview: new URLSearchParams(
'format=webp;jpg&width=438&height=250&position=entropy&quality=60&meta',
),
};
imagetools({
include: '**/*.{heic,heif,avif,jpeg,jpg,png,tiff,webp,gif}*',
defaultDirectives: (id) => {
// scan images without search params. These kind of images might be
// imported dynamically, where search params wont work.
if (id.search === '') {
if (id.pathname.includes('discretize-guides/guides/')) {
return directives.imagecardPreview;
}
}
return id.searchParams;
},
})
You don't add any search params to the imported picture at all, but instead do "the work" in the defaultDirectives.
Maybe this piece of info could help you to create a solution for your problem?
I believe this would potentially also be fixed by @rollup/plugin-dynamic-import-vars
stripping query strings before it tries to use your template string as a glob to resolve all possible files you could be importing, then appending them again afterwards.
If this type of "query string in file import" path pattern is common, perhaps that would be a reasonable feature request for rollup/plugins?
This is how Vite works and really isn't specific to imagetools at all. Vite can only handle static strings in imports and not dynamically constructed strings. Given that there isn't anything we can do about this in imagetools, I'm going to go ahead and close this
Although I guess it's supposed to work in some cases: https://vitejs.dev/guide/assets.html#new-url-url-import-meta-url. However, that case would be covered by https://github.com/JonasKruckenberg/imagetools/issues/327, so I'll leave this closed in favor of that issue.