Ad

How To Include Custom JS (AOS.js Specifically) In Rails 6

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!

Ad

Answer

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")
Ad
source: stackoverflow.com
Ad