DEV Community

Max Core
Max Core

Posted on • Updated on

SvelteKit: How to make code-based router, instead of file-based router [July 2022]

This is an old article. See newer instruction

Hello dudes.
Just wanted to share how do I route SvelteKit in JS.

In node_modules/@sveltejs/kit/dist/chunks/sync.js:471 there is an iteration over some units object that was constructed based on .svelte files in routes/ folder in order to construct some final a little bit more complex routes object, that will actually serve routes:

Array.from(units.values())
    .sort(compare)
    .forEach((unit) => {
        ...
        routes.push({...})
        ...
Enter fullscreen mode Exit fullscreen mode

console.log(units.values()) will give us something like:

[Map Iterator] {
  {
    id: '',
    pattern: /^\/$/,
    segments: [],
    page: { a: [Array], b: [Array] },
    endpoint: undefined
  },
  {
    id: '[id]',
    pattern: /^\/([^/]+?)\/?$/,
    segments: [ [Array] ],
    page: { a: [Array], b: [Array] },
    endpoint: undefined
  }
}
Enter fullscreen mode Exit fullscreen mode

So, the goal is to create our custom units somewhere, let's say urls and make SvelteKit iterate of it instead of units object.

So, what literally has to be done:

0) First, we have to check, that __layout.svelte at least with <slot/> tag inside, and __error.svelte already exist in our routes/ folder.
1) Create src/urls.jswith our routes, let's say — to home.svelte with '/' and article.svelte mapped by any string in browser's url:

const l = 'src/routes/__layout.svelte';
const b = ['src/routes/__error.svelte'];

const urls = [
    {pattern: /^\/$/, id: '', page: {a: [l, 'src/routes/home.svelte'], b }},
    {pattern: /^\/([^/]+?)\/?$/, id: '[id]', page: {a: [l, 'src/routes/article.svelte'], b }},
]

export default urls;
Enter fullscreen mode Exit fullscreen mode

2) In svelte.config.js:

import urls from './src/urls.js'; // <— add this

const config = {
  urls, // <— add this
  kit: {
    adapter: adapter()
  }
};
Enter fullscreen mode Exit fullscreen mode

3) In node_modules/@sveltejs/kit/dist/chunks/sync.js:

- Array.from(units.values())
-    .sort(compare)
+ Array.from(config.urls.values())
Enter fullscreen mode Exit fullscreen mode

IV. Install patch-package, so this changes will be automatically applied in future without manual hacks:

> npm i patch-package
> npx patch-package @sveltejs/kit
Enter fullscreen mode Exit fullscreen mode

package.json:

{
  ...
  "scripts": {
    ...
    "postinstall": "patch-package" // <— add this
Enter fullscreen mode Exit fullscreen mode

That's all!

Top comments (0)