Hello everyone, as part of the quick post series that I am doing (If you haven't seen my previous post, you can check Quickstart with Svelte 3).
So now it is time to implement a routing handle. This is normally the next step when we want to build our wonderful SPA with Svelve.
But first I want to talk about some options for routing that there are available and in that way, you can choose the best for your project.
Svelte routes options 🎨
These three guys are some of the most helpful libraries and frameworks that you can find when you need to work with the router.
- Sapper is a framework that helps you to build web applications and is powered by Svelte, so what does mean this? That you only need to install Sapper and you have a bunch of functionalities including routing.
- svelte-routing, This is a declarative Svelte routing library, and this one is the library that we will use in the post. I chose this because it's one of the libraries with more weekly Downloads in npm page.
- svelte-spa-router, An the last option is a module router, I think that this library has good advantages and one of these is that leverages hash-based routing.
So, now that we know some options that there are, we can jump to my favorite part.
Let's Code!! 🎧💻
Once that you have your base Svelte project running in your machine, the next step is to install the svelte-routing library, to do that just need to execute the following command
npm i svelte-routing
Create your routing and first pages
After that, we are ready to add some pages and start using the routing. At this point, we will divide into two points.
1. Create About and Home page
First, we will create a folder called pages
inside of src
, and then we will add two components, About.svelte
and Home.svelte
.
Here you can add some dummy code in your components, for me I will add this code and only will change the pageName
variable, feel free to copy if you want.
<script>
let pageName="Home Page";
</script>
<main>
<h1> {pageName}!</h1>
<p>Welcome this is my <b>{pageName}</b></p>
</main>
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
h1 {
color: #ff3e00;
text-transform: uppercase;
font-size: 4em;
font-weight: 100;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>
Your project needs to look something like this, after applying the previous changes.
2. Modify App.svelte
Now, it is time to modify our App.svelte
, here We will add our Router
configuration and also a small nav bar to navigate between our pages.
Here is very simple in the script section we will import the svelte-routing library with Router, Route, and Link components and also we will add our two pages.
<script>
import { Router, Route, Link } from "svelte-routing";
import Home from "./pages/Home.svelte";
import About from "./pages/About.svelte";
export let url = ""; //This property is necessary declare to avoid ignore the Router
</script>
Then we will set up the Router
with the navbar section and including two links to our pages.
<Router url="{url}">
<nav>
<Link to="/">Home</Link>
<Link to="about">About</Link>
</nav>
<div>
<Route path="about" component="{About}" />
<!--for now the router just support case sensitive,
one workaround colud be add two time the route
Example.
<Route path="About" component="{About}" />
-->
<Route path="/"><Home /></Route>
</div>
</Router>
If you want to find more information about the properties for each svelte-routing components, in this link, you can learn more.
So, now if you run your application we can navigate between Home page and About page, and also you will see a small navigation bar at the top.
The last setup
Wonderful!!, now your application is running. But there is a problem if you reload the About page, you will get a 404 error 😢, to fix that problem we need to do the following changes:
1. Create a server.js file
First, we need to create a server.js
file with the specifications that we found in the documentation of the library. Basically this code is to rendering the application all the time in the index.html, I leave the code over here.
// server.js
const { createServer } = require("http");
const app = require("./dist/App.js");
createServer((req, res) => {
const { html } = app.render({ url: req.url });
res.write(`
<!DOCTYPE html>
<div id="app">${html}</div>
<script src="/dist/bundle.js"></script>
`);
res.end();
}).listen(3000);
2. Set hydrate options as true
To do that we need to modify, fist our main.js
file with the property hydrate
.
// main.js
import App from './App.svelte';
const app = new App({
target: document.body,
hydrate: true
});
export default app;
And the second modification will be into rollup.config.js
file, here we'll specify that the application will be compiled as hydratable
.
// rollup.config.js
...
plugins: [
svelte({
hydratable: true,
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file - better for performance
css: css => {
css.write('public/build/bundle.css');
}
}),
...
Now the last modification is changing the start
script from the package.json
file, here we will add the -s
argument
// package.json
...
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "sirv public -s"
}
...
Great!, now everything should be work perfectly and your web application should be load from every page without any problem.
Conclusion 👨🎓
Svelte-routering is a great library, I think this is one of the best Routing libraries on the internet that helps us to add the routing functionality in our SPA with a minimal effort, but personally I recommend using this library if you want to create a small application with just a couple of pages and also you don't want to have all the power of a Framework.
However, if you are open to use a framework, Sapper is a great option, even if you planning to create a medium size project, with Sapper you will have great control of your application.
I hope that this small post was helpful for you and you can create your next application with Svelte.
Top comments (15)
This is a nice tutorial, helped me a lot.
hydratable is now inside the compilerOptions section in
svelte >= 3.0.0
below code might help
plugins: [
svelte({
preprocess: sveltePreprocess({ sourceMap: !production }),
compilerOptions: {
hydratable: true,
// enable run-time checks when not in production
dev: !production
}
}),
by the way to remind, you can import sveltePreprocess from svelte-preprocess after installed
Nice tutorial! ... I was wondering how I could change the current page's title? The way I understand until now is that the title comes from the public located file index.html, but it would be nice to have a different title according to the current page.
Good catch, definitely this is a great feature I will create a new post to explain how can we set a Title dynamically or if you already found a workaround I will be happy to see the implementation.
As an update, it is not necessary to use a
server.js
file; only add the option--single
to the scriptstart
like this:This is from the documentation of
sirv
npmjs.com/package/sirv-cli
Nice write up. Let me add to the discussion that there is another routing solution for svelte projects routify.dev/
Wow, I didn't know this library but looks very good. I saw the guide and the documentation and seems pretty easy to implement and also has nice features as
goto
,params
, and more.Thank you for share this new solution. 😃
by the time.. is routify better?
If you are hosting in a LAMP server use this trick
craete a .htaccess file in root folder with below code
FallBackResource index.html
this will work if your using the build output using this command
npm run build
also remember to use this code in your App.svelte file : Click Here
Hello, the Link pattern is easy, but how could I redirect to another route as a result of an action?
My scenario:
How can I invoke the link/route from typescript?
I found it ;-)
navigate()
For people getting console errors about hydratable, notice that the correct syntax in main.js is not: "hydrate: true", like in the blog post, but "hydratable: true"
My svelte app can finally reload pages! Thanks a lot!!!
Amazing!!!, also if you want to connect your app with Rest services, this link can help you.
dev.to/lukocastillo/svelte-3-how-t...
Where i need to put the server.js file?