How to access URL parameters in Sapper outside the script module

Suppose you are using Sapper to build a Svelte application and you have a dynamic page routing, for example/routes/[id].svelte.

You want to get the dynamic part of the URL (idIn this case) and you know that you canpreload()In function<script context="module">Part of the component:

<script context="module">
	export async function preload({ params }) {
		const { id } = params
	}
</script>

But the problem is that you need to use it externallypreload()To perform other operations.

The way to do this is to remove it frompreload, And use the usual method to define it as the props of the componentexport *syntax.

This is an example:

<script context="module">
	export async function preload({ params }) {
		const { id } = params
		return { id }
	}
</script>

<script> export let id

if (typeof window !== ‘undefined’) { alert(id) } </script>

Download mine for freeSlim Handbook


More subtle tutorials: