Search code examples
javascriptwebpackreferenceerrorlaravel-mixscrollreveal.js

ScrollReveal with webpack - ReferenceError: ScrollReveal is not defined


Using Laravel 5.6.29 with [email protected] & [email protected].

After installing [email protected] via npm i scrollreveal and requiring it in my app.js with require('scrollreveal'), I see that in my app.js output that ScrollReveal is there to be found.

However, when I try to initiate it with window.sr = ScrollReveal(); it throws me an error: ReferenceError: ScrollReveal is not defined, even though the reference comes after the definition.

I tried it with two different ways. First is to:

resources/assets/js/app.js

require('scrollreveal');
window.sr = ScrollReveal();

or the second way which is:

resources/views/index.blade.php

<script type="text/javascript" src="{{ mix('/js/app.js') }}"></script>
<script type="text/javascript">
window.sr = ScrollReveal();
</script>

However, if I just include the js the traditional way:

<script src="https://unpkg.com/scrollreveal/dist/scrollreveal.min.js"></script>

and then make a call to ScrollReveal(), it actually works.

Perhaps it's somehow a scope problem? But why would it only appear with ScrollReveal and not any other libraries I use? And isn't NodeJS require() function importing to global scope?

UPDATE: Third way I found that fixes this problem is by changing resources/assets/js/app.js and adding:

import ScrollReveal from 'scrollreveal';
window.sr = ScrollReveal();

will fix the issue, as this will in-scope define window.sr as ScrollReveal() using ES6 import (appearantly).

However, why wouldn't NodeJS require work still?


Solution

  • Made it work, in a way I don't yet know why it works (do elaborate if you know!), but it works.

    Changing resources/assets/js/app.js and adding:

    require('scrollreveal')().reveal('.sreveal');
    

    fixes the issue, using the NodeJS require().