Skip to content

svelte 5

config

To install SvelteJS without SvelteKit stuff, do not follow docs instruction to npm create svelte@latest

npm create vite@latest
# choice Svelte > Typescript
npm install svelte@next
# for Svelte5, vite-plugin-svelte v4.x is recommanded
npm install @sveltejs/vite-plugin-svelte@next

As of JUN24, pre-installed main.ts still use App component as class.
It should be modified.

main.ts
import { mount } from 'svelte'
import './app.css'
import App from './App.svelte'

const app = mount(App, { target: document.getElementById('app')!, })

export default app

migration

reactivity

# svelte 4
let var1 = ''
$: var2 = bool(var1)
# svelte 5
let var1 = $state('')
let var2 = $derived(bool(var1))

pagejs routing params

# svelte 4
export let params = {}
# svelte 5
let { params } = $props()

onMount() is not deprecated

onMount() is not deprecated in Svelte 5, only beforeUpdate()/afterUpdate() are. It is still the prefered pattern to call a function after initial page rendering.
Using $effect() is fine except if it triggers reactivity. In such case, a loop might occur. Event if it can be avoided with a control flag variable.

use-cases

dynamically load a script

To load a script in <HEAD> after a variable changed its state, <svelte:head> is not the way, because it is only read on page load.
Script has be added this way:

$effect(() => {
    if(condition) {
        const script = document.createElement('script')
        script.textContent = `console.log("Condition is: ${condition}");`
        document.head.appendChild(script)
    }
}