1

I'm new to Rails 6 + Webpack, so bear with me.

I'm trying to load aos.js into Rails 6, and then call it from a view file.

I've created javascript/custom/aos.js which contains this code with the following snippet appended:

console.log("typeof(AOS): " + typeof(AOS))

My application.js is here:

require("jquery")
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

require("custom/aos") // <===== The custom file I'm importing

var componentRequireContext = require.context("components", true);
var ReactRailsUJS = require("react_ujs");
ReactRailsUJS.useContext(componentRequireContext);
require("trix")
require("@rails/actiontext")

When I load my page, I get:

typeof(AOS): undefined so I know the file is being included, but AOS remains undefined.

However, when I include a javascript_include_tag with the CDN link, or simply paste the CDN code into the console, AOS is defined and everything works fine.

Why is AOS undefined when I require it in application.js? Thanks for your help!

1
  • 1
    At first glance at that file, AOS does not appear to be a local variable to the scope of the module; it's an export. Try const AOS = require('custom/aos') in the pack file instead.
    – rossta
    Mar 16, 2020 at 13:01

1 Answer 1

5

Just use YARN to install the package instead.

$ yarn add aos

And then import it in your own script where you use AOS:

// app/javascripts/pesky_scrolly_stuff.js
import AOS from 'aos';

document.addEventListener('DOMContentLoaded', function() {
  AOS.init({
    startEvent: 'turbolinks:load' // if you are using turbolinks
  });
});

And require your script into the pack:

// app/javascripts/packs/application.js
require("pesky_scrolly_stuff")
2
  • It works! Thanks for the explanation. I was trying to access AOS from the view itself. I guess webpack is not scoping AOS to window--any idea how to make AOS accessible from a view? Mar 16, 2020 at 19:42
  • 1
    Explicitly assign it to window. window.AOS = require('aos');. But then again you can just avoid shooting yourself in the foot by NOT putting JS in your views.
    – max
    Mar 16, 2020 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.