🧑💻 This article assumes you have intermediate experience with the command line.
Recently, I been working on a side-project, and I decided to build a single page application for it’s UI. So I wanted to share this information with y’all.
Previously, you would use something like svelte-navigator or svelte-spa-router, In fact, you can still use this tools today!
However, Sveltekit exists for a reason, and that is to have an opinionated way for building web applications with Svelte.
over the weekend we added an oft-requested feature to the SvelteKit beta: SPA mode, aka 'no SSR, please' : https://t.co/vWocTyNYsa
— Rich Harris (@Rich_Harris) March 29, 2021
(there's one final step we need to take before you can use it everywhere — thoughts welcome https://t.co/IgtWQ3Wfnl)
but there's more! 1/2 pic.twitter.com/ob4TPhhoiH
not an SPA fan either but it was a dealbreaker for a lot of folks. the alternative to supporting it is that people will invent their own solutions, most likely with other flaws
— Rich Harris (@Rich_Harris) March 29, 2021
As Rich Harris said, the Svelte framework creator, other solutions might have their flaws.
I won’t list the reasons why server-side rendering is better or when should you build an SPA instead. Every choice has it’s pros and cons.
Getting started
Let’s create a new project
The program will make you some questions, I will choosing the option that says “SvelteKit demo app”, and I will choose to use TypeScript.
I will skip any of the aditional options.
Open your favorite code editor with that folder. I will be using VS Code.
Don’t forget to install the packages.
How to enable SPA mode
You can also consult the official documentation in this link
Lets create the following file src/routes/+layout.ts
Add the following contents:
⚠ Do not confuse this file with
+layout.svelte
they’re different files, and only in the.ts
this will work.
Now we have to switch the adapter, to use the static one.
Open the file that contains the svelte config svelte.config.js
Replace the adapter to use the static one, here is how it should look like:
This should be enough to turn it into an SPA.
You can run the application if you want to play around with it.
How to dockerize any Single-page-application
TL;DR: Run any http server that allows rewrites and redirect everything to “index.html”.
Let’s do that! For that, I will using nginx.
✍ Create a file called nginx.conf
You can tune in this config if you want to, here you can see that it gives a long time cache for any static request.
Create a file called .dockerignore
Add the following contents:
Create a file called Dockerfile
As expected, the contents vary depending on the package manager you are using.
Let’s build the docker image:
Run the container with the following command:
This will forward the port “3000” from the container to match :3000 on your local computer.
🧠 Learn more about docker run
That should be all!
👋 Happy coding!