Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

External Svelte components lose reactivity from their stores when optimized by Vite #2064

Closed
mattjennings opened this issue Aug 1, 2021 · 1 comment

Comments

@mattjennings
Copy link

Describe the bug

When a library exports a component that uses an internal store from a .js file, that component loses reactivity unless excluded by Vite in optimizeDeps.

For example, say this is an add-numbers package:

// index.js
export { total, add } from './store'
export { default as Total } from './Total.svelte'

// store.js
import { writable } from "svelte/store";

export const total = writable(0);

export function add(number) {
  total.update((prev) => prev + number);
}
<!-- Total.svelte -->
<script>
  import { total } from "./store";
</script>

{$total}

and in your App, you use it like so:

<script>
  import { add, total, Total } from "add-numbers";
</script>

<button on:click={() => add(1)}>add</button>

Store: {$total}

Component: <Total />

$total will update correctly, however <Total /> does not.

If the imports are split up like this:

<script>
  import { add, total } from "add-numbers/store.js"
  import Total from 'add-numbers/Total.svelte'
</script>

<button on:click={() => add(1)}>add</button>

Store: {$total}

Component: <Total />

then it updates as expected. Otherwise, you need to pass the library into optimizeDeps.exclude in vite config.

Reproduction

https://github.com/mattjennings/svelte-kit-store-bug

Logs

No response

System Info

System:
    OS: macOS 11.4
    CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 357.08 MB / 16.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 16.3.0 - ~/.nvm/versions/node/v16.3.0/bin/node
    npm: 7.15.1 - ~/.nvm/versions/node/v16.3.0/bin/npm
  Browsers:
    Brave Browser: 92.1.27.109
    Chrome: 92.0.4515.107
    Safari: 14.1.1
    Safari Technology Preview: 15.0
  npmPackages:
    @sveltejs/kit: next => 1.0.0-next.139 
    svelte: ^3.34.0 => 3.41.0

Severity

serious, but I can work around it

Additional Information

I wasn't sure where to report this. If either the Svelte or Vite repo seems more appropriate, I can move this there.

@mattjennings
Copy link
Author

mattjennings commented Aug 1, 2021

Decided this is best to be in the vite-plugin-svelte repo. See: sveltejs/vite-plugin-svelte#124

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant