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({...}) ...
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 } }
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.js
with 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;
2) In svelte.config.js
:
import urls from './src/urls.js'; // <— add this const config = { urls, // <— add this kit: { adapter: adapter() } };
3) In node_modules/@sveltejs/kit/dist/chunks/sync.js
:
- Array.from(units.values()) - .sort(compare) + Array.from(config.urls.values())
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
package.json
:
{ ... "scripts": { ... "postinstall": "patch-package" // <— add this
That's all!
Top comments (0)