0

I am in the process of moving my entire application.js application into smaller page bundles using SplitChunks. In my users/show.html.erb page I am using the following tag to import the specific chunk.

<%= javascript_packs_with_chunks_tag 'users/show' %>

From the looks of my source code when I inspect it there are several bundles included such as the application.js file that includes jquery like this...

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

I am just testing the page to see if jquery is being loaded. My users/show.js code looks like this:

import "chartkick"
import "chart.js"

window.onload = function() {
  if (window.jQuery) {  
      // jQuery is loaded  
      alert("Yeah!");
  } else {
      // jQuery is not loaded
      alert("Doesn't Work");
  }
}

When I load the page I do see a Doesn't Work alert pop up indicating that jQuery has not been loaded. I'm newer to webpack so perhaps I have some misconfiguration somewhere, but if jquery is being loaded at the application.js level, why would my other pack not be able to listen to use jquery? Is this a problem with the dependency graphs?

My environment is as follows:

environment.js
const { environment } = require('@rails/webpacker');
const webpack = require('webpack');

environment.plugins.append('Provide', new webpack.ProvidePlugin({
 $: 'jquery',
 jQuery: 'jquery',
 Popper: ['popper.js', 'default']
}));
const config = environment.toWebpackConfig();
config.resolve.alias = {
 jquery: 'jquery/src/jquery'
};

environment.splitChunks()
module.exports = environment;
Trenton T
  • 75
  • 9

2 Answers2

0

I don't see where you add jQuery alias to your global (window) object. So you have to add it as below:

global.jQuery = jQuery; // This is a alias you defined in `ProvidePlugin`;
// window.jQuery = jQuery // also works

// Or you can add directly via your required object
const jquery = require('jquery');
global.jQuery = jquery;
tmhao2005
  • 14,776
  • 2
  • 37
  • 44
0

I invariably get this issue and here is the two lines which makes it working for me

// https://stackoverflow.com/q/54905026/398863
window.jQuery = $;
window.$ = $;
Amit Patel
  • 15,609
  • 18
  • 68
  • 106