Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

svelte-routing

EmilTholin63.4kMIT2.13.0TypeScript support: included

A declarative Svelte routing library with SSR support

svelte routing, svelte, sveltejs, route, router, routing, svelte route, svelte router, typescript

readme

npm

Svelte Routing

A declarative Svelte routing library with SSR support.

[CHANGELOG]

Install

npm i -D svelte-routing

Usage

<!-- App.svelte -->
<script>
  import { Router, Link, Route } from "svelte-routing";
  import Home from "./routes/Home.svelte";
  import About from "./routes/About.svelte";
  import Blog from "./routes/Blog.svelte";

  export let url = "";
</script>

<Router {url}>
  <nav>
    <Link to="/">Home</Link>
    <Link to="/about">About</Link>
    <Link to="/blog">Blog</Link>
  </nav>
  <div>
    <Route path="/blog/:id" component={BlogPost} />
    <Route path="/blog" component={Blog} />
    <Route path="/about" component={About} />
    <Route path="/"><Home /></Route>
  </div>
</Router>
// main.js
import App from "./App.svelte";

const app = new App({
    target: document.getElementById("app"),
});

API

Router

The Router component supplies the Link and Route descendant components with routing information through context, so you need at least one Router at the top of your application. It assigns a score to all its Route descendants and picks the best match to render.

Router components can also be nested to allow for seamless merging of many smaller apps.

Properties
Property Required Default Value Description
basepath | "/" The basepath property will be added to all the to properties of Link descendants and to all path properties of Route descendants. This property can be ignored in most cases, but if you host your application on e.g. https://example.com/my-site, the basepath should be set to /my-site.
url | "" The url property is used in SSR to force the current URL of the application and will be used by all Link and Route descendants. A falsy value will be ignored by the Router, so it's enough to declare export let url = ""; for your topmost component and only give it a value in SSR.
viewtransition | null View Transition (Experimental)

A component used to navigate around the application.

Properties
Property Required Default Value Description
to ✔ ️ "#" URL the component should link to.
replace | false When true, clicking the Link will replace the current entry in the history stack instead of adding a new one.
state | {} An object that will be pushed to the history stack when the Link is clicked.
getProps | () => ({}) A function that returns an object that will be spread on the underlying anchor element's attributes. The first argument given to the function is an object with the properties location, href, isPartiallyCurrent, isCurrent.
preserveScroll | false When true, clicking the Link will not scroll the page to the top.

Route

A component that will render its component property or children when its ancestor Router component decides it is the best match.

All properties other than path and component given to the Route will be passed to the rendered component.

Potential path parameters will be passed to the rendered component as properties. A wildcard * can be given a name with *wildcardName to pass the wildcard string as the wildcardName property instead of as the * property.

Potential path parameters are passed back to the parent using props, so they can be exposed to the slot template using let:params.

<Route path="/blog/:id" let:params>
    <BlogPost id="{params.id}" />
</Route>

The active status of link can be exposed to the slot template using let:active.

<Link to="/browser" let:active>
  <MenuItem active={active}>Browser</MenuItem>
</Link>
Properties
Property Required Default Value Description
path | "" The path for when this component should be rendered. If no path is given the Route will act as the default that matches if no other Route in the Router matches.
component | null The component constructor that will be used for rendering when the Route matches. If component is not set, the children of Route will be rendered instead.

A function that allows you to imperatively navigate around the application for those use cases where a Link component is not suitable, e.g. after submitting a form.

The first argument is a string denoting where to navigate to, and the second argument is an object with a replace, state and preserveScroll properties equivalent to those in the Link component.

<script>
    import { navigate } from "svelte-routing";

    function onSubmit() {
        login().then(() => {
            navigate("/success", { replace: true });
        });
    }
</script>

An action used on anchor tags to navigate around the application. You can add an attribute replace to replace the current entry in the history stack instead of adding a new one and preserveScroll to not scroll the page to the top when clicked.

<script>
    import { link } from "svelte-routing";
</script>

<Router>
    <a href="/" use:link>Home</a>
    <a href="/replace" use:link replace>Replace this URL</a>
    <!-- ... -->
</Router>

An action used on a root element to make all relative anchor elements navigate around the application. You can add an attribute replace on any anchor to replace the current entry in the history stack instead of adding a new one. You can add an attribute preserveScroll on any anchor to not to scroll the page to the top when clicked. You can add an attribute noroute for this action to skip over the anchor and allow it to use the native browser action.

<!-- App.svelte -->
<script>
    import { links } from "svelte-routing";
</script>

<div use:links>
    <Router>
        <a href="/">Home</a>
        <a href="/replace" replace>Replace this URL</a>
        <a href="/native" noroute>Use the native action</a>
        <!-- ... -->
    </Router>
</div>

viewtransition

Viewtransition for navigation (Experimental).

builtin transition

<script>
    import { fade } from "svelte/transition";
    // ...
</script>

<Router viewtransition="{() => { fn: fade, duration: 500 }}">
    <Route path="/" component="{Home}" />
    <Route path="/contact" component="{Contact}" />
</Router>

custom transition

<script>
    import { cubicin } from "svelte/easing";
    // ...
</script>

<Router
    viewtransition="{() => { duration: 500, easing: cubicin, css: (t) => `scale:${t};transform-origin:center center;` }}"
>
    <Route path="/" component="{Home}" />
    <Route path="/contact" component="{Contact}" />
</Router>

License

This project is licensed under the MIT.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for this project by you, shall be licensed as MIT, without any additional terms or conditions. Code of Conduct.

changelog

CHANGELOG

2.13.0

  • PR Merged #289.
  • Update dependencies.

2.12.0

  • PR merged #281.
  • Issue fixed #280.
  • Update dependencies.

2.11.0

  • PR merged #277.
  • Update dependencies.

2.10.0

  • PR removed #266.
  • Issue fixed #273.
  • Update dependencies.

2.9.0

2.8.0

  • PR merged #267.
  • PR merged #270.
  • Issue fixed #268.
  • Issue fixed #269.
  • Update dependencies.

2.7.0

  • PR merged #266.
  • Update dependencies.

2.6.0

  • Issue fixed #262.
  • PR merged #263.
  • Update svelte version.

2.5.0

  • Issue fixed #260.
  • Update svelte version.

2.4.0

  • Fixed viewtransition callback function error.

2.3.0

  • Added prettier.
  • Added view transition (Experimental).

2.2.0

2.1.0

  • PR merged #256.
  • PR merged #257.
  • Issue fixed #254.
  • Update svelte version.

2.0.0

  • PR merged #250.
  • PR merged #247.
  • Removing example folder.
  • Update svelte version.

1.11.0

  • PR merged #245.
  • Update svelte version.

1.10.0

1.9.0

  • Major improvement in performance. Minimize unnecessary prefetch components.

1.8.9

  • Fixed. Sometimes navigate return info null.
  • Issue fixed #132.

1.8.8

  • Issue fixed #242.
  • PR removed #77 Causing infinity loop in nested routes.

1.8.7

  • Segment mismatch bug fixed.

1.8.6

  • Issue fixed #242.
  • Update svelte version.
  • Codebase improved.

1.8.5

  • Can Use Dom function improved.
  • function & class mismatch bug fixed.

1.8.4

1.8.3

  • Hooks & Types bugs fixed.

1.8.2

  • Svelte dependency updated.
  • Lazyload component return type added.
  • Issue fixed #240.

1.8.0

  • Major Bugs fixed in Router.svelte.
  • Converted all interfaces into types.
  • Improved Lazy Loading/Async Route Import. Get much smaller chunk for every route. Only load files (JS & CSS module) when URL is active.
<!-- App.svelte -->
<Route path="/" component={() => import("./Home.svelte")} />

<Route path="/about" component={() => import("./About.svelte")} />

<Route path="/user/:user" component={() => import("./User.svelte")} />
  • Added Hooks for Contexts. useLocation, useRouter, useHistory.
<!-- Page.svelte -->
<script>
    import { useLocation } from "svelte-routing";
    const location = useLocation();
</script>

<div>{JSON.stringify($location)}</div>

1.7.0

  • Added Code of Conduct.
  • Optimized the codebase.
  • Update the dependencies.
  • PR merged #220.
  • PR merged #210.
  • PR merged #206.
  • PR merged #192.
  • PR merged #188.
  • PR merged #175.
  • PR merged #173.
  • PR merged #158.
  • PR merged #105.
  • PR merged #95.
  • PR merged #85.
  • PR merged #77.
  • PR/Issue #200, Tested & it's not relevant/exists.
  • Issue fixed #122, #4652.

1.6.0

Added TypeScript support.

1.4.0

Added functionality for passing the location to the rendered Route component and slot.

<!-- App.svelte -->
<Route path="/blog" component="{Blog}" />

<!-- Blog.svelte -->
<script>
    import queryString from "query-string";

    export let location;

    let queryParams;
    $: queryParams = queryString.parse(location.search);
</script>

<h1>Blog</h1>
<p>{queryParams.foo}</p>

<!-- App.svelte -->
<Route path="/blog" let:location>
    <h1>Blog</h1>
    <p>{location.search}</p>
</Route>

1.3.0

Added functionality to pass potential Route path parameters back to the parent using props, so they can be exposed to the slot template using let:params.

<Route path="/blog/:id" let:params>
    <BlogPost id="{params.id}" />
</Route>

1.2.0

Added functionality for passing all the extra Route properties to the rendered component.

<!-- App.svelte -->
<Route path="/page" component="{Page}" foo="foo" bar="bar" />

<!-- Page.svelte -->
<script>
    export let foo;
    export let bar;
</script>

<h1>{foo} {bar}</h1>

1.1.0

Added the ability to give Route path wildcards a custom name.

<!-- App.svelte -->
<Route path="/page/*wildcardName" component="{Page}" />

<!-- Page.svelte -->
<script>
    export let wildcardName;
</script>

<h1>{wildcardName}</h1>

1.0.0

  • Moved to Svelte 3.
  • It's now required for all Route and Link components to have a Router ancestor.
  • NavLink was removed in favour for a more versatile Link component. Check the userland NavLink component in the example directory for an example.
  • The SSR component no longer needs to be compiled at runtime with the help of esm as there is no longer a dependency on the history library. You can compile a separate CJS bundle for the server and pass in a prop to the topmost component and use that as the url property for the Router, which will force the URL for all descendants.
  • All component filename extensions have been changed to .svelte.
  • Hash routing is no longer supported.
  • The entire API of the library is now exported from the src/index.js file, so importing from the library is now much more pleasant.
import { Router, Route, Link } from "svelte-routing";

0.4.0

Moved to Svelte v2 and added the new link and links actions.

0.3.0

Split the createHistory function into createBrowserHistory, createMemoryHistory, createHashHistory to allow for better tree shaking of unused history creation code.

0.2.0

Added the ability to access the match object in a matched route:

<!-- App.html -->
<Route path="/:myParam" bind:match>
    <h1>{{match && match.params.myParam}}</h1>
</Route>

or:

<!-- App.html -->
<Route path="/:myParam" component="{{MyComponent}}" />

<!-- MyComponent.html -->
<h1>{{match.params.myParam}}</h1>

0.1.0

Added the ability to give a component constructor to a route with the component property:

<!-- App.html -->
<Route path="/:myParam" component="{{MyComponent}}" />