Home > Web Front-end > JS Tutorial > body text

Experiences and Caveats of Svelte igration

Barbara Streisand
Release: 2024-11-04 10:46:30
Original
836 people have browsed it

Experiences and Caveats of Svelte igration

I have recently updated a rather complex web application. The application has features like auth, Stripe, i18n, dark/light mode, PWA, etc. Overall, it has around 30 pages and components, with almost no third-party npm packages.

I would like to point out what I found quite challenging when migrating the app to Svelte 5.

Auto-Migration Script Hammer

The auto-migration script provided by Svelte can do the job for you with this "one-liner" command in the terminal npx sv migrate svelte-5 (after you do all the necessary updates and installs: "@sveltejs/vite-plugin-svelte": "^4.0.0" and "svelte": "^5"). But I do not recommend this "hammer" approach.

Go file by file, component by component with Ctrl Shift P (Windows/Linux) / Shift Command P (Mac) and use the Migrate Component to Svelte 5 Syntax command in the VS Code command palette instead. You will have more control that way.

Deprecated run() Surprise

The script cannot perform miracles. Upgrading reactive variable declarations to $state() is usually fine. However, the script may struggle to detect whether $: should be converted to $derived()/$derived.by(() => {}) or $effect(() => {}).

So, guess what? With the auto-migration script, you might end up with lots of run(() => {}).

For example, imagine as a simplified example using something like this:

<script>
...
   let notext = false;
   $: if (data.completeDoc == 'NoLangVersion') {
      notext = true;
   }
   $: if (data.completeDoc !== 'NoLangVersion') {
      notext = false;
   }
</script>

...
{#if notext}
   {data.userPrefferedLang.noTextWarning}
{:else}
...
{/if}
...
Copy after login
Copy after login

The auto-migration script will give you this:

<script>
    import { run } from 'svelte/legacy';
...
    let notext = $state(false);
    run(() => {
        if (data.completeDoc == 'NoLangVersion') {
            notext = true;
        }
    });
    run(() => {
        if (data.completeDoc !== 'NoLangVersion') {
            notext = false;
        }
    });
</script>
Copy after login
Copy after login

with a nice little warning that the run function is deprecated.

The better Svelte 5 code would be this I guess:

<script>
...
    let notext = $derived.by(() => {
        if (data.completeDoc == 'NoLangVersion') {
            return  true;
        }
        if (data.completeDoc !== 'NoLangVersion') {
            return false;
        }
    });
...
</script>
Copy after login
Copy after login

or if your code is not really complicated even somehting like this:

<script>
...
    let notext = $derived(
        data.completeDoc == 'NoLangVersion' 
        ? 
        true
        :
        false
        ) 
...
</script>
Copy after login
Copy after login

The reason is that the script cannot transform code to $derived.by(() => {}) easily, so it would like to use a more dirty approach with $effect(). But $effect() runs only client-side, so the script uses the deprecated run function instead.

Avoid $effect If You Can

Now we are getting to the most important takeaway. Which is $effect() running only client-side. So no $effect() on the server, for prerendering pages and SSR.

$effect() DOES NOT RUN ON THE SERVER!

This should be really emphasized in the Svelte 5 documentation.

Look at this two examples:

<script>
let a = 1
let b = 2

$: c = a + b
</script>

{c}  // server responds with c == 3
Copy after login
Copy after login
<script>
let a = $state(1)
let b = $state(2)
let c = $state(0)

$effect(() => {
  c = a + b
})
</script>

{c}  // server responds with c == 0
Copy after login
Copy after login

They are not the same. This causes a lot of challenges. The client will need to reevaluate the c variable when mounting the page. The page will look different when sent from the server and when finally DOM-rendered on the client (SSR, SEO, flicker issues, etc.).

So always try to use $derived or $derived.by(() => {}) over $effect(). It will save you lots of trouble.

It's quite the same story as when we were discouraged from using stores in SvelteKit and SSR.

$effect vs onMount() in SvelteKit

You might be tempted to replace your onMount() in SvelteKit with $effect() thanks to the examples that were given during the arrival of Svelte 5. For the reasons already mentioned, I would discourage this for the time being. onMount is still a a core Svelte lifecycle hook.

$bindable $props Surprise

The other nice surprise is that Svelte 5 takes care to have consistent variable values. If you pass a variable as a prop to a component and change this variable in the component later on, the script will try to solve this inconsistency using $bindable $prop. The parent should be notified, so your app state is consistent.

Look at this example:

<script>
...
   let notext = false;
   $: if (data.completeDoc == 'NoLangVersion') {
      notext = true;
   }
   $: if (data.completeDoc !== 'NoLangVersion') {
      notext = false;
   }
</script>

...
{#if notext}
   {data.userPrefferedLang.noTextWarning}
{:else}
...
{/if}
...
Copy after login
Copy after login

The autou-migration script will want you to use a component with binded value to ensure the parent may get the updated value back:

<script>
    import { run } from 'svelte/legacy';
...
    let notext = $state(false);
    run(() => {
        if (data.completeDoc == 'NoLangVersion') {
            notext = true;
        }
    });
    run(() => {
        if (data.completeDoc !== 'NoLangVersion') {
            notext = false;
        }
    });
</script>
Copy after login
Copy after login

But maybe we can use quite simpler way as well, you guessed it, with $derived():

<script>
...
    let notext = $derived.by(() => {
        if (data.completeDoc == 'NoLangVersion') {
            return  true;
        }
        if (data.completeDoc !== 'NoLangVersion') {
            return false;
        }
    });
...
</script>
Copy after login
Copy after login

:global { } Block

A very nice feature that I found during migration was that we can use CSS :global with block now. Styling with :global is quite necessary if you want to style the HTML elements in @html, for example.

So instead of this:

<script>
...
    let notext = $derived(
        data.completeDoc == 'NoLangVersion' 
        ? 
        true
        :
        false
        ) 
...
</script>
Copy after login
Copy after login

you can use this:

<script>
let a = 1
let b = 2

$: c = a + b
</script>

{c}  // server responds with c == 3
Copy after login
Copy after login

Style as a Prop in Components

In Svelte 4, if you wanted to provide a CSS class as a prop to a component, you would use {$$props.class}:

<script>
let a = $state(1)
let b = $state(2)
let c = $state(0)

$effect(() => {
  c = a + b
})
</script>

{c}  // server responds with c == 0
Copy after login
Copy after login

In Svelte 5 you may use class={className}:

// parent svelte file
<script>
   import ComponentBinded from './ComponentBinded.svelte';
   import ComponentWithDerived from './ComponentWithDerived.svelte';
   let name = $state('John Wick');
</script>

<p>Name value in parent: {name}</p>

<ComponentBinded bind:name={name} />

<ComponentWithDerived {name} />
Copy after login

Possible Lighthouse Perfomance Drop

When I used the auto-merging script, I was shocked at how my app's performance dropped. With Svelte 4, I had nearly all 100%s. It was only after I manually migrated and carefully considered how (mainly how to avoid $effect() if possible) that my Lighthouse scores were back in the green again.

Final Words

It took longer to migrate to Svelte 5 than I had expected. I still have not pushed this new version to production, though. The updates to Svelte 5 are still coming in with quite high frequency.

I hope my experience may be useful to others.

The above is the detailed content of Experiences and Caveats of Svelte igration. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template