Top Related Projects
Declarative routing for React
🥢 A minimalist-friendly ~2.1KB routing for React and Preact
🤖 Fully typesafe Router for React (and friends) w/ built-in caching, 1st class search-param APIs, client-side cache integration and isomorphic rendering.
Quick Overview
Svelte-routing is a declarative routing library for Svelte applications. It provides a simple and intuitive way to handle client-side routing in Svelte projects, allowing developers to create single-page applications with multiple views and navigation.
Pros
- Lightweight and easy to integrate into Svelte projects
- Supports nested routes and route parameters
- Provides a declarative API that aligns well with Svelte's component-based approach
- Includes useful features like programmatic navigation and route guards
Cons
- Limited documentation compared to some other routing libraries
- May not be as feature-rich as more established routing solutions
- Requires manual setup of server-side routing for proper SPA behavior
- Relatively small community compared to React or Vue routing libraries
Code Examples
- Basic route setup:
<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";
</script>
<Router>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/blog">Blog</Link>
</nav>
<main>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/blog" component={Blog} />
</main>
</Router>
- Using route parameters:
<script>
import { Router, Route } from "svelte-routing";
import BlogPost from "./routes/BlogPost.svelte";
</script>
<Router>
<Route path="/blog/:id" let:params>
<BlogPost id={params.id} />
</Route>
</Router>
- Programmatic navigation:
<script>
import { navigate } from "svelte-routing";
function handleClick() {
navigate("/dashboard");
}
</script>
<button on:click={handleClick}>Go to Dashboard</button>
Getting Started
-
Install the library:
npm install svelte-routing
-
Set up your main App component:
<script> import { Router, Link, Route } from "svelte-routing"; import Home from "./routes/Home.svelte"; import About from "./routes/About.svelte"; </script> <Router> <nav> <Link to="/">Home</Link> <Link to="/about">About</Link> </nav> <main> <Route path="/" component={Home} /> <Route path="/about" component={About} /> </main> </Router>
-
Create your route components (e.g., Home.svelte and About.svelte) in the routes folder.
-
If using a static file server, configure it to serve your index.html for all routes to support SPA behavior.
Competitor Comparisons
Declarative routing for React
Pros of react-router
- Larger community and ecosystem, with more resources and third-party integrations
- More advanced features like nested routing and data loading
- Supports both client-side and server-side rendering
Cons of react-router
- More complex API, which can be overwhelming for beginners
- Heavier bundle size due to additional features
- Requires more setup and configuration compared to svelte-routing
Code Comparison
react-router:
import { BrowserRouter, Route, Link } from "react-router-dom";
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</BrowserRouter>
);
}
svelte-routing:
<script>
import { Router, Link, Route } from "svelte-routing";
</script>
<Router>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
</Router>
Both libraries offer similar basic routing functionality, but react-router provides more advanced features and flexibility at the cost of increased complexity. svelte-routing offers a simpler, more lightweight solution that integrates seamlessly with Svelte's component-based architecture.
Pros of reach/router
- More mature and widely adopted in the React ecosystem
- Supports nested routing and relative links
- Provides accessibility features out of the box
Cons of reach/router
- Specifically designed for React, not optimized for Svelte
- Larger bundle size due to additional features
- May require more setup and configuration
Code Comparison
reach/router:
import { Router, Link } from "@reach/router"
const App = () => (
<Router>
<Home path="/" />
<Dashboard path="dashboard" />
</Router>
)
svelte-routing:
<script>
import { Router, Link, Route } from "svelte-routing";
</script>
<Router>
<Route path="/" component={Home} />
<Route path="dashboard" component={Dashboard} />
</Router>
Key Differences
- Syntax: reach/router uses JSX, while svelte-routing uses Svelte's template syntax
- Integration: svelte-routing is specifically designed for Svelte, offering better integration
- Simplicity: svelte-routing provides a more straightforward API for basic routing needs
- Performance: svelte-routing likely has better performance in Svelte applications due to its lightweight nature and Svelte-specific optimizations
Conclusion
While reach/router offers more features and wider adoption, svelte-routing is the better choice for Svelte projects due to its seamless integration and optimized performance within the Svelte ecosystem.
🥢 A minimalist-friendly ~2.1KB routing for React and Preact
Pros of wouter
- Framework-agnostic: Works with React, Preact, and other libraries
- Lightweight: Smaller bundle size (1.5kB vs 3kB for svelte-routing)
- More flexible: Supports custom hooks and location strategies
Cons of wouter
- Less Svelte-specific optimizations
- Fewer built-in features compared to svelte-routing
- May require additional configuration for Svelte projects
Code Comparison
svelte-routing:
import { Router, Link, Route } from "svelte-routing";
<Router>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
</Router>
wouter:
import { Router, Link, Route } from "wouter";
<Router>
<nav>
<Link href="/">Home</Link>
<Link href="/about">About</Link>
</nav>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
</Router>
Both libraries offer similar syntax for basic routing, with minor differences in attribute names (e.g., to
vs href
for links). wouter's framework-agnostic approach may require additional setup for Svelte-specific features, while svelte-routing provides a more tailored experience for Svelte applications out of the box.
🤖 Fully typesafe Router for React (and friends) w/ built-in caching, 1st class search-param APIs, client-side cache integration and isomorphic rendering.
Pros of TanStack Router
- Framework-agnostic, supporting React, Vue, and Solid.js
- Advanced features like type-safe routing and automatic code-splitting
- Active development and community support
Cons of TanStack Router
- Steeper learning curve due to its more complex API
- Potentially overkill for simple routing needs in Svelte projects
- Less Svelte-specific optimizations and integrations
Code Comparison
svelte-routing:
import { Router, Link, Route } from "svelte-routing";
<Router>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
</Router>
TanStack Router:
import { Router, Link, Route, RootRoute } from '@tanstack/router'
const rootRoute = new RootRoute()
const indexRoute = new Route({
getParentRoute: () => rootRoute,
path: '/',
component: Home,
})
const aboutRoute = new Route({
getParentRoute: () => rootRoute,
path: '/about',
component: About,
})
const routeTree = rootRoute.addChildren([indexRoute, aboutRoute])
const router = new Router({ routeTree })
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Svelte Routing
A declarative Svelte routing library with SSR support.
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) |
Link
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. |
navigate
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>
link
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>
links
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.
Top Related Projects
Declarative routing for React
🥢 A minimalist-friendly ~2.1KB routing for React and Preact
🤖 Fully typesafe Router for React (and friends) w/ built-in caching, 1st class search-param APIs, client-side cache integration and isomorphic rendering.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot