Search code examples
svelteassetssveltekit

SvelteKit: How to use asset paths imported via JSON file?


I am trying to build my SvelteKit application for production but I have trouble with using my image assets.

I have got a Json file pointing to all my asset's paths, which I am importing into my Svelte components.

This is the error I get.

and I would like to use them as such:

<script>
    import Images from "/src/contentrain/Images/Images.json";  
</script>

<div class="hero-items">
    <div class="hero">
        <div class="hero-content flex-col lg:flex-row z-20">
            <div class="card bg-base-100 p-10">
                <figure class="px-10 pt-10">
                    <img src={Images[12].Path} draggable="false" alt="img" class="rounded-xl" />

Can someone teach me about asset routing?


Solution

  • If you are not importing the asset directly, Vite will not copy it over to the assets folder upon building. With an example:

    If you don't:

    import myImage from "/src/somefolder/myImage.png";
    

    Then myImage.png will not be in the output folder after building with Vite.

    Furthermore, the path changes. This means that you need a JSON for paths when developing, and another JSON for paths when deploying.

    Since you don't want to abandon your Images.json file, I suggest that:

    1. You move your images to the static folder, whose contents should be copied over to the root of your website.
    2. You get fancy with your configuration. You can use wj-config to create environment-aware configuration objects that will automatically change according to the specified environment.