woutdp / live_svelte

Svelte inside Phoenix LiveView with seamless end-to-end reactivity
https://hexdocs.pm/live_svelte
MIT License
1.02k stars 38 forks source link

Using libraries that require the window object. #139

Closed threeaccents closed 6 days ago

threeaccents commented 6 days ago

Versions:

      {:phoenix, "~> 1.7.12"},
      {:phoenix_html, "~> 4.0"},
      {:phoenix_live_view, "~> 0.20.2"},
      {:bandit, "~> 1.2"},
      {:live_svelte, "~> 0.13.2"}

I'm trying to integrate leaflet into a LiveSvelte program. I've tried both using the V sigil and the custom svelte component approach; however, I always end up running into this error when importing leaflet

[error] ** (NodeJS.Error) window is not defined
ReferenceError: window is not defined
    at /home/threeaccents/work/threeaccents/code/threeaccents/hub/priv/svelte/server.js:164:23
    at /home/threeaccents/work/threeaccents/code/threeaccents/hub/priv/svelte/server.js:36:71

This happens as soon as I try to import leaflet.

Do I need the server.js file if I won't be doing ssr? I removed it from being built in the built.js file. Not sure if this is the right approach. I'm probably missing something obvious. I'm not too familiar with the FE ecosystem anymore.

tonydangblog commented 6 days ago

This error is common when using SSR. You have a couple options:

  1. You can disable SSR. From the README:

Disabling SSR SSR is enabled by default when you install LiveSvelte. If you don't want to use Server-Side Rendering for Svelte, you have 2 options:

Globally If you don't want to use SSR on any component you can disable it globally. This will automatically be the case if you don't include the NodeJS supervisor in the application.ex file

Component To disable SSR on a specific component, set the ssr property to false. Like so:

<.svelte name="Example" ssr={false} />

  1. If you want to keep SSR, you can dynamically import Leaflet in an onMount.
onMount(async () => {
  const leaflet = await import('leaflet');

  // Your leaflet code here...
});

Here's a link to a more detailed example using SvelteKit. Note: I've only tried this approach in a SvelteKit app, but pretty sure it should work with LiveSvelte as well. Hope this helps!

threeaccents commented 6 days ago

Thank you that is exactly what I was looking for!

woutdp commented 6 days ago

@tonydangblog Thank you :fire: