2

I have a standard Sapper project like that:

routes
├── application
   ├──- index.svelte
   ├──- _brush.js
   ├──- (...etc)

I wish to install the library 'dat.gui' to my project and I have installed:$ npm install --save dat.gui with success.

<script>
    import { onMount } from 'svelte';   
    import { Brush } from './_brush.js';
    import * as dat from 'dat.gui';

    // dat.GUI
    let brushParams = { ... my chosen params}

    onMount(()=> {
        // loading dat.GUI
        let gui = new dat.GUI();
        console.log(gui);
    }

The Sapper application keeps crashing all the time with the following message: ReferenceError: window is not defined at Object...etc.

Which should be the right way to import a library like that into sapperjs ? Thank you

1 Answers1

4

Sounds like dat.gui crashes if you require it in Node. I'd argue that's a bug, and encourage you to raise an issue — just because it needs a DOM in order to do anything doesn't mean it should blow up if the module is imported in an environment without a DOM.

We can work around it, though. Instead of having a static import, you can dynamically import it inside your onMount (which doesn't run on the server):

<script>
    import { onMount } from 'svelte';   
    import { Brush } from './_brush.js';

    // dat.GUI
    let brushParams = { ... my chosen params}

    onMount(()=> {
        import('dat.gui').then(dat => {
            // loading dat.GUI
            let gui = new dat.GUI();
            console.log(gui);
        });
    }
</script>
Rich Harris
  • 28,091
  • 3
  • 84
  • 99
  • This is great news Rick! It worked like a charm and I learned something new ;) Thank you so much. Problem solved...with the workaround. – Bernat Ferragut Jan 16 '20 at 01:47