Instantclick Is Not Defined On Rails 6

I try to integrate instantclick to my rails 6 application. I added the instantclick.js file in my javascript/custom folder. Then, I import it in javascript/packs/application.js:


I added to the end of the body tag of my layout the following line to initialize instantclick:

            <script data-no-instant>InstantClick.init();</script>

Then, I get the following error in console:

(index):404 Uncaught ReferenceError: InstantClick is not defined

I'm new to using webpacker, maybe I did something wrong. However, the instantclick.js file is imported. Any idea what I'm doing wrong? Thanks.



Webpack works differently than Sprockets. One thing you're running into is that webpack does not expose anything to the global scope. That means calling functions from a script tag won't work as expected unless you instruct webpack to add those variables to the window object.

Your instantclick.js file is also not module-aware, i.e, it does not export anything, such as with module.exports = InstantClick.

With webpack though, you can configure it to do both. You'll need to both export and exposeInstantClick:

yarn add expose-loader exports-loader
// config/webpack/environment.js

const { environment } = require('@rails/webpacker')

environment.loaders.append('InstantClick', {
  test: /instantclick/,
  use: [{
    loader: 'expose-loader',
    options: 'InstantClick'
    loader: 'exports-loader',
    options: 'InstantClick'

module.exports = environment

There is more to learn and other ways you can do it of course. Here are some resources: