Svelte: Router Support

Created on 10 Dec 2016  ·  64Comments  ·  Source: sveltejs/svelte

Is there any official router, except the router example app?

docs

Most helpful comment

Really feel like Svelte's maintainers are shooting themselves in the foot by not having an official router. I understand we can use whatever we want and make it work, or use Sapper. But there is a lot of people out there that don't want to go into the whole Sapper and SSR complexities are held back by the lack of an official svelte router. I was too.
I really think something along the lines of vue router would make svelte much more complete as a solution for a lot of developers.

All 64 comments

No official router yet, no. Personally I've always tended to take a view-agnostic approach to routing (i.e. use a generic router, handle view setup/update/teardown inside route handlers) but I can see the value of having a recommended way to solve the problem – something along the lines of vue-router.

I was thinking declarative router is easier to reason about and implement for validations.

<router ref:home method="get" url="{{path1}}/{{path2}}/{{path3}}?query={{param4}}" />
<router protocol="ws" message="..." />
<router protocol="https" method="get" certs="..." />
<script>
... validate numbers and string, return contents
</script>
<group access="public">
   <router ref:home method="get" url="{{path1}}/{{path2}}/{{path3}}?query={{param4}}" />
</group>

In server folder, only admin can access this router:
<group access="private">...</group>

Sharing my Ractive routing lib (as a possible inspiration to a new one in Svelte)

I've already implemented a routing system to load components called Altiva, 100% based on Ractive (along with rcu and Page.js in the background).


The (original) syntax

var app = new Altiva()

/* Define areas that your app can use  */
app.areas( [ 'header', 'left_menu', 'content', 'footer', 'optional_modal' ] )

/* Define each route and its components */
app.route( '/',
{
    header: 'MainHeader',
    content: 'Feed',
    footer: 'MainFooter'
});

/* Note that you don't have to use all areas, but only the desirable ones */
app.route( '/login',
{
    content: 'Login'
});

/* Here, the routing system is started, after the "compilation" of all routes */
app.start();

It has middlewares as well, including jwt auth middlewares, svg link compatibility, and other things that I can detail if/when appropriate.


How it works and why it's ready to Svelte's build time

In each app.route call, a vanilla js function is compiled and registered in the routing library, specific for the route.

When the user navigates to a route, this specific function is called, which loads only the necessary components and areas for the route. _(and areas with the same component are untouched)_

Similar to Svelte, the library itself is not used at run time, only the code it generates (the above mentioned functions) and I can adapt and/or refactor it to be used in Svelte's build time.


@Rich-Harris , it would be an honor to develop (a proposal of) a routing system to Svelte (as a plugin or core feature).

I am not an advanced javascript developer, though, and I am refactoring all my code because I've learned a lot since my first implementation.

I think routing is a different concern than Svelte is trying to address, and I don't know that a Svelte-branded router is going to add to the feel-good factor of this "anti-framework". Rich himself suggested that it is a separate concern.

That said, I am working on building my own app using Svelte and definitely had to solve the problem of routing. What I've come up with, though far from complete, aims to provide a very similar API to vue-router or the Angular 2 router (ahem, new router version 3, is it?), while being friendly to the Svelte component API, while still being framework-agnostic.

See https://github.com/sawbladejs/example for example usage with Svelte.

Like I said, it's early in development, documented only through the tests, probably still buggy, and limited to hash-based URLs at the moment. But, if you're interested in it, please feel free to jump in and help out.

https://github.com/sawbladejs/sawblade

It's not "official", but abstract-state-router has Svelte support.

It is a renderer-agnostic router for the framework-averse.

As I understand svelte has no runtime, so we can use any routing library we want, so what is the purpose of "official" one? :) Use olde good page.js or your own preferred lib, that's the way :)

One reason for an "official" one is support from the library.

Hey, I've been supporting abstract-state-router for longer than Svelte has been around ;-P

Wow, it looks like there _is_ a svelte-router after all. ;-)

For some definition of "router", you may be interested in svelte-querystring-router

Sapper is sort of an official blessed router, plus an official blessed bunch of other stuff. Closing this, we can reopen if someone disagrees.

@Conduitry how we can use Sapper routing without Node.JS on the backend?

You can't. I wasn't really thinking about that. I guess I'll reopen this, but I'm personally not holding my breath for some non-Sapper routing solution.

Is it possible to cut page routing form Sapper and store to independent package or merge with Svelte?
For my opinion, we should have a common solution for Svelte routing.

I don't think a router is necessarily something that should be included in Svelte's core, but could we at least get a recommended library or an officially supported component/set of components (similar to Virtual List)?

For those looking, Svelte Routing is pretty solid.

Published my example of using Navigo for client-side routing https://github.com/ilog2000/svelte-navigo

This question is asked frequently enough in the gitter forums and elsewhere, I think we ought to document alternative solutions and call it a day.

I've started using the navigo solution suggested by @ilog2000 across all my apps, as I've encountered reloading errors with the other listed solutions. Would be beneficial to have documented guidance I think.

Might as well pitch in my page.js powered approach. Uses the same nested <svelte:component> structure as sapper because it's real good, but using a more fully-featured standalone routing library for all the niceties that brings.

https://github.com/tivac/svelte-routing

I am using Svelte-Sapper for routing. While it works great it's not what I was expecting. I was hoping for hashed routing similar to ember which keeps the application truly single paged.
I found https://www.npmjs.com/package/svelte-router to not work well. But that could just be me!!!

Also interested in non-sapper router solution.

How about any existing router? I’m using pagejs for example.

@PaulMaly, I was using page.js a lot, since 2014. But I am probably going to use https://github.com/lukeed/navaid from now on, and this is my first recommendation for everyone right now.

@paulocoghi unfortunately, features not enough...

This was literally the first thing I looked for when I started evaluating Svelte. Without having any client side blessed router I cannot even consider using this, even that from other parts the project looks promising.

From my point of view frontend framework needs view for showing / modifying state and a router... then as a bonus would come nice development scripts and testing solutions etc.

Hopefully someone (sorry I don't have time for that right now) releases some more complete svelte stack in future 👍 Or is the e.g. https://github.com/TehShrike/abstract-state-router way to go (I love the idea having router completely separated, but would prefer that there is one that is good enough)?

@elhigu If you want a 'blessed' stack, go for Microsoft .NET. The reason there is no blessed router is because Svelte works with anything, that's the point. It is unopinionated.

If you want a full, built together Svelte stack complete with router and SSR, look at Sapper.

The fact is, all of the routers above work fine, pick the one with the features you need.

For that kind of blessed stack for me Vue.js would be enough instead of going vendor locked fullstack to the .NET.

Reason why I commented here was that this issue is still not closed, so looks like Svelte developers thinks that this actually is an issue that should be addressed.

Here is some more motivation... no need to read, since it is not really important.

React is also unopinionated but there are quite many blessed (or too many unholy) routing choices, but they are pretty clear stating that they specifically work with React and there are project templates to select good combination of componenets. Hard part is that you need huge time to try to select some good set :(

So for me and many others, some officially preferred set from svelte developers would have been just fine. In that case it is easier to trust judgement of people who has written the framework instead of having to trust some random blogger who has tested how some stuff might work together without having long experience on the any of related libraries.

If Svelte as unopinionated framework lists in their page some blessed libraries that works well together it doesn't make Svelte any less unopinionated. It only signals that developers of Svelte has found that some other libraries work really well combined with it.

If you want a full, built together Svelte stack complete with router and SSR, look at Sapper.

Sounds interesting, so that would be defacto .NET fro svelte? I will look into it, but I really don't want tight backend integration this time so might not be for me.

@elhigu Sapper isn't designed as a backend, it's a Server-side rendered frontend. It means the user can get a fast, snappy experience on any device. You can do it in React/Vue too but IMHO they don't support it as well.

I understand your point about things being blessed so that they 'work together' but I reiterate that one of the goals of Svelte as I understand it, is to work with whatever you have/want, and not try to lock you in (and lock third party libs out).

I don't think this issue will amount to the 'board of Svelte' knighting a series of third party routers, so much as enhancing the list of routers you might want to look at in the Svelte Awesome repository's readme.

Thanks @antony for clarifications and correcting my assumptions. So maybe this issue should be closed after all as there is nothing to do about this on Svelte side.

+1 on closing the issue, we intergrated with page.js without any hickups,
works like a charm.

Thanks, :)

On Mon, Feb 4, 2019, 10:22 AM Mikael Lepistö <[email protected]
wrote:

Thanks @antony https://github.com/antony for clarifications and
correcting my assumptions. So maybe this issue should be closed after all
as there is nothing to do about this on Svelte side.


You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/sveltejs/svelte/issues/172#issuecomment-460334661,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AHwSnTbIM_LXDnSzGixzfNgtPvUjmhNvks5vKGxkgaJpZM4LJmAv
.

This was literally the first thing I looked for when I started evaluating Svelte. Without having any client side blessed router I cannot even consider using this, even that from other parts the project looks promising.

From my point of view frontend framework needs view for showing / modifying state and a router... then as a bonus would come nice development scripts and testing solutions etc.

Hopefully someone (sorry I don't have time for that right now) releases some more complete svelte stack in future 👍 Or is the e.g. https://github.com/TehShrike/abstract-state-router way to go (I love the idea having router completely separated, but would prefer that there is one that is good enough)?

I can sympathize with this. Almost all alternatives mentioned here haven't been updated in months or years, and most seem to be static routing libs, I'd much prefer dynamic routing similar to react-router. The svero package is close to it, but it's lacking on features, and has some quirks.

@pablote, take a look at Sapper. https://sapper.svelte.dev/

Sapper doesn't support react-router-style dynamic routing, and I don't think it's particularly likely to any time soon, as that makes things like code splitting more complicated to do well. If you think Svero is close to what you want you could open issues there and work with the author to figure out what else you think is missing.

@pablote, take a look at Sapper. https://sapper.svelte.dev/

I did, I saw it being suggested, but that seems to be a complete different thing. I don't think the answer to needing simply routing should be, put this whole thing on top of it.

Sapper doesn't support react-router-style dynamic routing, and I don't think it's particularly likely to any time soon, as that makes things like code splitting more complicated to do well. If you think Svero is close to what you want you could open issues there and work with the author to figure out what else you think is missing.

Sure, yes. Something more officially supported would be awesome though :)

For what it's worth, I'll be updating abstract-state-router's svelte adapter soon to work with v3.

I have published a clientside router for Svelte.
It's framework agnostic and works with React, Vue and Svelte.
Features:

  • Built in animations
  • ExpressJS-like syntax.
  • Middleware via familiar app.use()

Github
https://github.com/alshdavid/crayon

Animated example
https://github.com/alshdavid/crayon/tree/master/examples/svelte-animated

Non-animated example
https://github.com/alshdavid/crayon/tree/master/examples/svelte

Basic syntax sample

import crayon from 'crayon'
import svelte from 'crayon/svelte'
import MyView from './MyView.svelte'

const app = crayon.create()

app.use(svelte.router())
app.use(crayon.animate({
    name: 'fade',  
    duration: 300
}))

app.path('/', (req, res) => res.mount(MyView))

app.load()

If you like it, please star the repo and contribute!

And there is my component-based router to keep advanced things done in the seconds, like before leave blocking, hash routing and throttling for lazy loading and better ux.

https://github.com/qutran/swheel

Simple Svelte Router for Single Page Applications (SPA), inspired by Vue Router. Features include:

  • Nested route/view mapping.
  • Modular, component-based router configuration.
  • Route params, query, wildcards (powered by path-to-regexp).
  • Navigation guards for navigation control.
  • Links with automatic active CSS classes.
  • HTML5 history mode or hash mode (powered by history).

https://github.com/spaceavocado/svelte-router

Do any of these routers easily support true app style transitions? What I mean by this is having elements that are persistent in different views persist from each view and animate between said views.

The canonical example of this would be a list of blog posts with hero images in the post cards, and when the user clicks on one of the cards the image would then animate between two states, growing in size and changing position, so that by it's final state it now occupies the position of the hero in the actual post.

Here are a few examples and articles and libraries to check out what I'm talking about:

http://lkzhao.com/2017/02/05/hero-interactive-transition.html

https://github.com/HeroTransitions/Hero

You will notice if you dig into this a bit that doing this kind of thing on native is pretty common, but almost non-existent on the web, so just asking to see if the Svelte community has these kinds of things in mind at all. I think one main issue with this is that the web is 'page' based, not 'view' based, so maybe this kind of thinking is a bit foreign to the web crowd. Not sure, though.

Anyway, any thoughts on the matter would be great :-)

😳

no, I have not...thanks!!! 🤗

Crayon supports route transitions
https://github.com/alshdavid/crayon
Crayon

@Conduitry @Rich-Harris, Sapper is awesome. But what if you need to serve a non-static client from an Apache or NGINX server?

As suggested various times in this thread it'd be nice if Svelte had an official router, like in Vue: https://router.vuejs.org/

Shouldn't we maybe extrapolate the routing code from Sapper and put it in its own package, that can then become a dependency? Maybe that could be the official Svelte router.

Sapper could internally just keep the code necessary to interpolate the routing module and the file system.

Any chance of that coming soon? Could we re-open this issue?

If we have built-in directives for CSS transitions, it seems that having a router would be higher in the list of useful features for real-world applications.

Citing Chris (https://youtu.be/AdNJ3fydeao?t=1980):

This is the kind feature that most frameworks don't include. And the reason for that is because in the JavaScript world we're very conscious of bundle size [...] but it means that we're restricting the number of features that we're including in our frameworks. But Svelte is a compiler, it doesn't have the same constraints. If you don't use a particular feature [...] then we don't need to include the code that makes that feature possible.

Thanks! :)

@pensierinmusica please see: https://github.com/sveltejs/svelte/wiki/FAQ#is-there-a-router

For those also wondering which router to use for a simple static SPA, I ended up using this https://github.com/ItalyPaleAle/svelte-spa-router and it's great so far.

(edit: ^ svelte-spa-router is listed in the official FAQ too)

Please, check the most of available router solutions here: https://github.com/ryanatkn/awesome-svelte-resources#routers

Really feel like Svelte's maintainers are shooting themselves in the foot by not having an official router. I understand we can use whatever we want and make it work, or use Sapper. But there is a lot of people out there that don't want to go into the whole Sapper and SSR complexities are held back by the lack of an official svelte router. I was too.
I really think something along the lines of vue router would make svelte much more complete as a solution for a lot of developers.

@nitroboy720 I would be happy to develop a svelte routing solution that handles:

  1. SSR
  2. SPA Routing
  3. Hot Reloading
  4. Code-splitting
  5. Webpack?

@DominusVilicus it sounds like your idea has a lot of crossover with the routify project mentioned above. You might want to chat to the team in their discord about helping out.

We're not looking for anybody to develop a specific router for Svelte, by the way, there are plenty of good solutions out there, feel free to create your own.

There are plans to bless / endorse a specific router in the future, but whether that is an existing one or one created from fresh has not yet been decided.

I recommend discussion around routing and routers should continue in the Svelte Discord

@antony I don't want file-based routing. I would like to manually configure routes, like with vue-router. I basically want a vue-router for svelte.

Simple solution: this sapper issue has a fairly easy fix and by fixing it, this router support issue would automatically be taken care of and could be closed. It is probably worth the trouble to fix it asap, since it is such a simple fix and seeing how often both of these issues are brought up.

@DominusVilicus

@nitroboy720 I would be happy to develop a svelte routing solution that handles:

  1. SSR
  2. SPA Routing
  3. Hot Reloading
  4. Code-splitting
  5. Webpack?

I don't think it is needed, all of that has already been solved by other solutions, and what we need is to just unify them. I think Sapper is closest, since all it needs is to support non-ssr spa.

@DominusVilicus We really have all kinds of routers, check this list:

component-based router (React-like): svelte-routing
config-based router (Vue-like): svelte-page-router
file-based router (Sapper-like): routify
state-based router: svelte-pathfinder

@PaulMaly they don't fit my requirements.

I've started my own router and it's coming along. It will be similar to vue-router, and it will support SSR, SPA Routing, Hot Reloading, Code-splitting & lazy-loading and be based on webpack

@DominusVilicus Would it be possible to base it on Rollup instead of Webpack? _(offtopic)_

@DominusVilicus Actually, most of these features are not directly related to the router itself, but related to the bundler. For example, code-splitting is based on dynamic imports, lazy-loading is based on bundler built-in loader (eg. in Webpack) or 3rd-party solution (Rollup doesn't have built-in loader). SSR is the feature of a framework, not a router, but of course, a router should work on the server.

Seems, svelte-page-router already supports all these things. I believe, the other routers also, mostly. Also, for things like code-splitting & lazy-loading we've stand-alone, router-agnostic loadable components like svelte-viewpoint.

Not to mention that lazy-loading isn't always desirable, that is a feature you would want to the ability to toggle.

@paulocoghi yes, I plan to add rollup support too.

@PaulMaly SSR is related to routing, you need a server-side solution for javascript routing for SSR to work correctly for your router (so I am building a History API for the server-side)

@pngwn Yeah, it will be user-defined. Lazy-loading / dynamically-importing / code-splitting pages is recommended though as you only download pages that you specifically need: eg { path: '/about', component: ()=>import('@/pages/about')}

Oh like that, I think all routers that I have used support that. Mostly a bundler feature.

Yeah, well the main thing is that there is a lot of people coming from Vue js, and for that transition to be easy, there must be tooling similar to vue-router.

As @nitroboy720 mentioned, the maintainers are shooting themselves in the foot by not having a recommended router solution like vue-router.

That being said, I would be more than happy to assist in the community development of the equivalent

That may change in the future. It is highly unlikely it would be like Vue router though. The problem with most routers is not the interface or code splitting.

Svelte Easyroute is v2.0 now!
TL;DR it is a config-based router (like Vue Router).

  • Nested routes
  • CSS transitions
  • Hooks
  • Lazy component loading

Check it out here: Svelte Easyroute

@lyohaplotinka https://github.com/sveltejs/integrations rather than a dead github issue ;)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

thoughtspile picture thoughtspile  ·  3Comments

AntoninBeaufort picture AntoninBeaufort  ·  3Comments

robnagler picture robnagler  ·  3Comments

clitetailor picture clitetailor  ·  3Comments

ricardobeat picture ricardobeat  ·  3Comments