sveltejs / rollup-plugin-svelte

Compile Svelte components with Rollup
MIT License
505 stars 79 forks source link

Svelte Lifecycle Functions Not Being Called as Expected #215

Closed matusbarany04 closed 1 year ago

matusbarany04 commented 1 year ago

Description:

In my Svelte component, I've implemented several lifecycle functions like onMount, onDestroy, beforeUpdate, afterUpdate, and tick. Only onDestroy and tick are being called inside a console, the other lifecycle functions aren't producing any output.

Steps to Reproduce:

Create a following Svelte component with all the lifecycle functions:

<script>
  import { onMount, beforeUpdate, afterUpdate, onDestroy, tick } from 'svelte';

  let count = 0;

  onMount(() => {
    console.log("onMount: Component has mounted");
  });

  beforeUpdate(() => {
    console.log(`beforeUpdate: About to update. Current count: ${count}`);
  });

  afterUpdate(() => {
    console.log(`afterUpdate: State has updated. Current count: ${count}`);
  });

  onDestroy(() => {
    console.log("onDestroy: Component will be destroyed");
  });

  async function increment() {
    count += 1;
    await tick();
    console.log(`tick: DOM updated after incrementing count to ${count}`);
  }
</script>

<button on:click={increment}>
  Increment ({count})
</button>

It seems like the bundle.js file created from rollup config doesn't include any of the other functions

function instance$2($$self, $$props, $$invalidate) {
        let count = 0;

        onDestroy(() => {
            console.log("onDestroy: Component will be destroyed");
        });

        async function increment() {
            $$invalidate(0, count += 1);
            await tick();
            console.log(`tick: DOM updated after incrementing count to ${count}`);
        }

        return [count, increment];
}

Expected Behavior:

The console should show logs from all lifecycle functions: onMount, beforeUpdate, afterUpdate, and tick.

Actual Behavior:

Only the tick and onDestroy are called

Additional Information:

Svelte version: 4.2.0
rollup-plugin-svelte version : 7.1.6
matusbarany04 commented 1 year ago

It seems to have been a problem with svelte 4 imports

https://github.com/sveltejs/svelte/issues/8953

changing import {onMount} from "svelte"; to import {onMount} from "svelte/internal"; fixed my issue

dummdidumm commented 1 year ago

Do this instead: https://github.com/sveltejs/svelte/issues/8953#issuecomment-1629963893