Search code examples
sveltesveltekit

How to deploy a svelte static site in a subfolder?


I'm using SvelteKit to build a very little static website that I deploy manually via SFTP.

When in dev mode, the website is located at the route's root : http://localhost:4173/

But when I deploy it the website is located at : http://example.com/svelte/ and the links and images point to / instead of /svelte.

I read that I should use the base variable with npm run build --base=/svelte but do I have to use it in every <a href={base}/link> and <img src={base}/images/…> ?

Is there a way to automatically prepend the base option on every links and images ?


Solution

  • As the docs state regarding links:

    If you find yourself writing this often, it may make sense to extract this into a reusable component.

    So yes, just create a component that includes it for you.

    For images I would not recommend using paths like that anyway. Instead use import in the script to get a URL (for unknown types you might have to configure Vite to treat the extension as an asset).

    That way the image will be emitted with a hash, so if you change it at any point you will not run into caching problems (the old image being loaded in the browser).

    <script>
      import image from '$lib/images/image.jpg';
    </script>
    <img src={image} ... />