/** * Only needed for the demo environment development. * * It is not needed for including the router package in your project. */ if (import.meta.hot) { import.meta.hot.accept(() => { import.meta.hot!.invalidate(); }); }
/** * This is a state variable that will hold the router instance. * * It can be used to access the current route, navigate, etc: */ letrouter: RouterInstance = $state();
/** * Get notified when the current route changes: */ constroute = $derived(router.current); $effect(() => { if (router.current) { logging.info( `🚀 I'm an $effect in app.svelte and i'm running because the current route is now ${router.current.result.path.original}!` ); } });
/** * Let's declare our routes for the main app router: */ constroutes: RouteConfig[] = [ { // You can name your routes anything you want for tracking or debugging: name:"default-route", hooks: { pre:async (route: RouteResult) => { console.log(`redirecting to ${session.mode==="hash"?"/#":""}/home using a pre hook!`, route); goto(`${session.mode==="hash"?"/#":""}/home`); } } }, { // Here we use a regex to match the home route. // This is useful if you want to match a route that has a dynamic path. // The "?:" is used to group the regex without capturing the match: // path: /^\/($|home)$/, path:"home", component:Home, // Use hooks to perform actions before and after the route is resolved: hooks: { pre:async (route: Route): Promise<boolean> => { // console.log("pre hook #1 fired for route"); returntrue; // Return true to continue down the route evaluation path. }, // Hooks can also be an array of functions (async too): post: [ // This is a post hook that will be executed after the route is resolved: (route: Route): boolean=> { // console.log("post hook #1 fired for route"); returntrue; // Return true to continue down the route evaluation path. }, // This is an async post hook that will be executed after the route is resolved: async (route: Route): Promise<boolean> => { // console.log("post hook #2 (async) fired for route"); returntrue; // Return true to continue down the route evaluation path. } ] } }, { path:"nested", component:Nested }, { path:"paths-and-params", component:PathsAndParams }, { path:"protected", component:Protected }, { path:"transitions", component:Transitions } ];
// This is a global pre hook that can be applied to all routes. // Here you could check if the user is logged in or perform some other // authentication checks: constglobalAuthGuardHook = async (route: Route): Promise<boolean> => { console.warn("globalAuthGuardHook", route); // Return true so that the route can continue down its evaluation path. returntrue; }; </script>
Svelte action to handle routing with optional active state.
Similar to active
Add
use:route
to an anchor element to handle routing and optionally manage active state.Example
Source