Search code examples
javascriptruby-on-railsruby-on-rails-6webpackerwow.js

What is the correct way to use wow.js in Rails 6 with webpacker?


I am trying to use wow.js with my Ruby on Rails 6.1.3.2 project. I have installed wowjs with Yarn and I see it in my node_modules folder.

I have imported wowjs into my application app/javascript/packs/application.js

import WOW from 'wowjs';
require("wowjs/css/libs/animate.css") 

I have a script.js file located at this path: app/javascript/script.js and initiates WOW

    wow = new WOW({
        animateClass: 'animated',
        offset: 100
    });
    wow.init();

script.js is imported into app/javascript/packs/application.rb after wowjs is imported like this:

import WOW from 'wowjs';
require("wowjs/css/libs/animate.css")
import "scripts.js"

I keep getting the following error in the console:

scripts.js:514 Uncaught ReferenceError: WOW is not defined
at Object.<anonymous> (scripts.js:514)
at Object../app/javascript/scripts.js (scripts.js:897)
at __webpack_require__ (bootstrap:63)
at Module../app/javascript/packs/application.js (application.js:1)
at __webpack_require__ (bootstrap:63)
at bootstrap:198
at bootstrap:198

I have other modules that I have installed in a similar manner that are not throwing errors. I'd like to understand what the "rails way" of doing this is. Thanks in advance for your assistance.


Solution

  • The answer to this question was ultimately the following:

    Move the import statements from application.js to scripts.js where the modules were being used:

    import "splitting/dist/splitting.css";
    import "splitting/dist/splitting-cells.css";
    import Splitting from "splitting";
    

    I was missing the declaration of 'wow' as a 'var'. So I added 'var' to the script.js like this:

    var wow = new WOW({
        animateClass: 'animated',
        offset: 100
    });
    wow.init();
    

    The key lesson for me was that the import statements needed to be at the top of the script that was consuming the modules. I had assumed that just by virtue of them being imported into application.js that was enough to make them available to all scripts. Perhaps that was a newbie lesson. Many thanks to @rossta for some important guidance. I'm looking forward to his soon coming The Webpacker Course.