Reputation: 1326
I'm trying to import a JSON file on my Vite app, whose paths are dynamically generated. So the import
path for this JSON includes variables.
I know it's possible to do it with require
, but I'm working with Svelte, and I cant use requires.
Upvotes: 1
Views: 3258
Reputation: 184607
You can use a dynamic import()
statement for that. This will return a promise, which has to be awaited, though. E.g.
<script lang="ts">
import meta from './meta.json';
const filePromise = import(/* @vite-ignore */ `./${meta.file}.json`);
</script>
{#await filePromise then file}
{file.property}
{/await}
There are some limitations to dynamic imports in Vite so the application can be built properly. The @vite-ignore
comment silences a warning output about these limitations.
Upvotes: 3