How to set up routing in a Svelte app using svelte-routing

Svelte is a popular JavaScript framework for building user interfaces. Routing is a crucial aspect of web development, enabling the creation of dynamic and interactive single-page applications. In the context of Svelte, routing plays a pivotal role in navigating between different views or components seamlessly.

The svelte-routing framework is the most commonly used framework with Svelte for routing because it is made particularly for Svelte and for routing in Svelte. We will also use this framework to set up routing in a basic Svelte application.

Note: The examples below have Svelte and svelte-routing already installed and set up for simplicity.

To get started, the first thing that we need to do is to install the Svelte Router. To do so, we use the following command:

npm install --save svelte-routing

Setting up routes

Once the router is installed, we can create a basic routing structure in our Svelte app. We will start by defining routes.

<!-- App.svelte -->
<script>
  import { Router, Route } from 'svelte-routing';
  import HomePage from './Homepage.svelte';
  import Profile from './Profile.svelte';
  import Information from './Information.svelte';
</script>

<Router>
  <Route path="/" component={HomePage} />
  <Route path="/profile" component={Profile} />
  <Route path="/information" component={Information} />
</Router>
Setting up routes using svelte-routing

Code explanation

  • Line 3: We import the necessary components from the svelte–routing library, including Router and Route.

  • Lines 4–6: We import the Svelte components associated with each route.

  • Line 9: We use the Router component to wrap the route definitions.

  • Lines 10–12: We define routes for the home page (/), about page (/profile) and contact page (/information) and associate them with the HomePage, Profile, and Information components, respectively.

Creating route components

Now, we need to create separate Svelte components for each route. Below, we have created simple components for the home, profile, and information page routes.

<!-- Information.svelte -->
<style>
  h2 {
    color: #000000;
  }
</style>

<h1>Information Page</h1>
Creating Svelte components

Navigating between routes

To navigate between routes, we will use the Link component from the Svelte Router. It simplifies the process of navigating between different routes. The to prop of the Link component specifies the target route or location that the link should navigate to. It can be an absolute path or a relative path. Let's look at an example below:

<!-- Homepage.svelte -->
<script>
  import { Link } from 'svelte-routing';
  export let user_name = 'Guest';
</script>

<h1>Welcome {user_name} to Educative!</h1>

<p>Explore more about us:</p>
<nav>
  <Link to="/profile">Profile</Link>
  <Link to="/information">Information</Link>
</nav>
Using the Link component for routing

Code explanation

  • Line 3: We import the Link component from svelte–routing, which is used for creating navigation links between routes.

  • Lines 4: We export a variable named user_name that can be passed to the HomePage component, allowing for dynamic content in the component.

  • Line 10: We use the nav component to wrap the navigation links.

  • Lines 11–12: We create a link to the profile route (/profile) and information route (/information). Clicking this link will navigate to the corresponding route.

Note: In the example, /profile and /information are relative paths, indicating that the links navigate to the Profile and Information routes, respectively.

Let's look at the complete working example below:

# This repo is no longer maintained. Consider using `npm init vite` and selecting the `svelte` option or — if you want a full-fledged app framework — use [SvelteKit](https://kit.svelte.dev), the official application framework for Svelte.

---

# svelte app

This is a project template for [Svelte](https://svelte.dev) apps. It lives at https://github.com/sveltejs/template.

To create a new project based on this template using [degit](https://github.com/Rich-Harris/degit):

```bash
npx degit sveltejs/template svelte-app
cd svelte-app
```

*Note that you will need to have [Node.js](https://nodejs.org) installed.*


## Get started

Install the dependencies...

```bash
cd svelte-app
npm install
```

...then start [Rollup](https://rollupjs.org):

```bash
npm run dev
```

Navigate to [localhost:8080](http://localhost:8080). You should see your app running. Edit a component file in `src`, save it, and reload the page to see your changes.

By default, the server will only respond to requests from localhost. To allow connections from other computers, edit the `sirv` commands in package.json to include the option `--host 0.0.0.0`.

If you're using [Visual Studio Code](https://code.visualstudio.com/) we recommend installing the official extension [Svelte for VS Code](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode). If you are using other editors you may need to install a plugin in order to get syntax highlighting and intellisense.

## Building and running in production mode

To create an optimised version of the app:

```bash
npm run build
```

You can run the newly built app with `npm run start`. This uses [sirv](https://github.com/lukeed/sirv), which is included in your package.json's `dependencies` so that the app will work when you deploy to platforms like [Heroku](https://heroku.com).


## Single-page app mode

By default, sirv will only respond to requests that match files in `public`. This is to maximise compatibility with static fileservers, allowing you to deploy your app anywhere.

If you're building a single-page app (SPA) with multiple routes, sirv needs to be able to respond to requests for *any* path. You can make it so by editing the `"start"` command in package.json:

```js
"start": "sirv public --single"
```

## Using TypeScript

This template comes with a script to set up a TypeScript development environment, you can run it immediately after cloning the template with:

```bash
node scripts/setupTypeScript.js
```

Or remove the script via:

```bash
rm scripts/setupTypeScript.js
```

If you want to use `baseUrl` or `path` aliases within your `tsconfig`, you need to set up `@rollup/plugin-alias` to tell Rollup to resolve the aliases. For more info, see [this StackOverflow question](https://stackoverflow.com/questions/63427935/setup-tsconfig-path-in-svelte).

## Deploying to the web

### With [Vercel](https://vercel.com)

Install `vercel` if you haven't already:

```bash
npm install -g vercel
```

Then, from within your project folder:

```bash
cd public
vercel deploy --name my-project
```

### With [surge](https://surge.sh/)

Install `surge` if you haven't already:

```bash
npm install -g surge
```

Then, from within your project folder:

```bash
npm run build
surge public my-project.surge.sh
```
Routing in a basic Svelte application

We've seen how to set up routing in a Svelte application using svelte-routing. By integrating routes and components, we can create a seamless navigation experience for our users.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved