Svelte 3 - How to integrate with svelte routing

lukocastillo

Luis Castillo

Posted on May 8, 2020

Svelte 3 - How to integrate with svelte routing

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.

  1. 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.
  2. 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.
  3. 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
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Your project needs to look something like this, after applying the previous changes.
First 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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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.

Alt Text

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);
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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');
            }
        }),
        ...
Enter fullscreen mode Exit fullscreen mode

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"
  }
...
Enter fullscreen mode Exit fullscreen mode

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.

πŸ’– πŸ’ͺ πŸ™… 🚩
lukocastillo
Luis Castillo

Posted on May 8, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related