Reputation: 151
I am trying to import all urls for images in a directory in a wildcard fashion, with two possible extensions:
import urls from "../static/images/**/*.{png,svg}";
Currently there are three files in this directory, importing them individually works fine. When I use this syntax, the files are not found:
Failed to resolve import "../static/images/**/*.{png,svg}" from "src/routes/index.svelte". Does the file exist?
I had heard that it was possible to do this out of the box in SvelteKit, do I need to enable or define the pattern of import in jsconfig.json file in order to achieve this functionality, or install a dependency?
Upvotes: 7
Views: 4595
Reputation: 151
Fixed by changing import to use meta.glob:
const urls = import.meta.glob("../static/images/**/*.{png,svg}");
Upvotes: 8
Reputation: 3788
I know this question is already solved and old, But I want to add more info (for what worked for me, so if someone in the future will have my same bug, can easily solve it using also mine)
using the @Daniel Veihelmann answer solved my issue (for svelte components)
basically, I have to set { eager: true }
or it will give you undefined
and I used this code:
<script>
const modules = import.meta.glob("./Pages/*.svelte", { eager: true });
const pages = Object.keys(modules).map((key) => modules[key].default);
</script>
{#each pages as page}
<svelte:component this={page} />
{/each}
now I dynamically rendered all the pages from a folder. (you can use the same approach for images and render them using each block if you want)
Upvotes: 3
Reputation: 1477
In my case, I additionally had to set the eager option to true
to load all components in a certain folder:
const components = import.meta.glob('./../lib/test/**.svelte', { eager: true });
Without this option, I always received an empty object.
Upvotes: 3