Search code examples
ruby-on-railsrubyyarnpkgwebpackeralertifyjs

Rails 6 + Webpacker + Yarn: problem to load javascript libraries


I'm having trouble to configure javascript library's on rails 6 using webpacker and yarn. I tried with momentjs and alertifyjs but both returned the same error for me, Idk where is my error.

For example: I tried to add an alert library to my project. I did the following steps:

yarn add alertifyjs

I added require in application.js:

require ('alertifyjs');

In my application.html.erb, the javascript pack tag are in:

<% = javascript_pack_tag 'application', 'data-turbolinks-track': 'reload'%>

If I enter in the page and see the rendered JS file along with the page, the alertifyjs code is there, but when trying to instantiate a new alert, I get the following error:

alertify.alert('Ready!');

ReferenceError: Can’t find variable: alertify

The same occurred with momentjs.

My nodemodules folder hierarchy after yard add alertifyjs: alertifyjs folder hierarchy

Thanks!


Solution

  • I solved the problem!

    I was missing to import and put the variable global to be able to access outside of the application.js

    import alertify from 'alertifyjs';
    global.alertify = alertify;