How to run a Svelte app from a subfolder?

Viewed 2660

I am hosting a svelte app in GitHub pages, so its served from a subfolder. The problem is that all links aren't working anymore. Basically I need to change the base URL of the app, but I don't know how to do that in svelte or rollup.

P.S : I am not using Sapper.

2 Answers

You can use the base element for this.

Either set it directly in your index.html or use svelte:head to set it in the svelte app itself, this allows to easily change it according to development/production

<svelte:head>
  <base href="BASEURL">
</svelte:head>

To set it according to the environment you can use something like environment variables and @rollup/plugin-replace but I feel that is outside the scope of this question. But you can look here Environment variables in svelte + rollup

Svelte-Navigator (Routing)- You can check here, [https://github.com/mefechoel/svelte-navigator][1]. you can set basepath directly in the Router, then it will read all the URLs with that base path only.

<Router basepath="/base">
    <Link to="profile">Go to /base/profile</Link>
    <Link to="blog">Go to /base/blog</Link>
    <Route path="blog" component={Blog} />
    <Route path="profile" component={Profile} />
</Router>

Here "/base" is your subfolder name, for example if your svelte app running at port localhost:5000, by setting base path you can change it to localhost/base

Related