Svelte 3 – How to integrate with svelte routing

Svelte routes options

  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.

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>
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>

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"
  }
...

Leave a comment

Your email address will not be published. Required fields are marked *