2

What I tried:

  1. I tried work around it via if (browser), more specifically{ if (!browser) { let DailyIframe = await import('daily-co/daily-js) } in the load function inside <script context="module"> ) so the code is always executed on the server). Then pass it as a prop to a component. However, although it worked on the server, the local dev environment re-runs the load function (which has to return an empty prop as it never imported anything) and overrides DailyIframe's value (might be a bug with Vite/SvelteKit).

  2. I tried to import the library in an end-point e.g. api.json.js instead, which is always executed on the server. However, it has to return a json, and I can't pass an entire library variable onto it.

After research It seems like a combination of problems from Vite, SvelteKit and certain libraries where global is undefined: SvelteKit With MongoDB ReferenceError: global is not defined)

But I cannot use his solution of putting it in an endpoint, because I need the DailyIframe and the mic audio stream from the client to create a video conference room

Also, why would certain libraries Daily (and looking at other related Stackoverflow posts, MongoDB) throw this error in the first place, while other libraries are safe to use?

Anyway suggestion is appreciated!

Elton Lin
  • 77
  • 1
  • 10

1 Answers1

3

Why ?

Vite doesn't include shims for Node builtins variables.

Read suggestion to understand:

Anyway suggestion is appreciated!

In index.html add :

<script>
  var global = global || window;
</script>

then for example in App.svelte :

<script>
import { onMount } from 'svelte'
import DailyIframe from '@daily-co/daily-js'
    
onMount(async () => {
  let callObject = DailyIframe.createFrame()
  const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
  let recorder = new MediaRecorder(stream)
  recorder.start()
})
</script>

Demo

https://stackblitz.com/edit/sveltekit-1yn6pz?devtoolsheight=33

logs preview

logs preview of the room connection

flydev
  • 4,327
  • 2
  • 31
  • 36
  • 2
    Thanks - binding global = window, or importing with CDN worksaround the issue! "Some libraries incorrectly rely on node globals being available because they expect to be built in node, but to run in the browser. " - paraphrased from your reading suggestions – Elton Lin Dec 04 '21 at 14:33
  • This didn't work for me. I found another solution (that also didn't work) here: https://dev.to/richardbray/how-to-fix-the-referenceerror-global-is-not-defined-error-in-sveltekitvite-2i49 – Eric Dela Cruz Jan 05 '22 at 09:56
  • @EricDelaCruz I added a demo to the answer, open it and then check the console, you will see a lot of errors comming from the call which try to connect to a innexistant room. – flydev Jan 05 '22 at 10:57