MrFrenzoid
MrFrenzoid

Reputation: 1326

How to dynamically import a json file

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.

enter image description here

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

Answers (1)

brunnerh
brunnerh

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

Related Questions