Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migrating Rails from Asset Pipeline to Webpacker: Uncaught ReferenceError: $ is not defined in rails-ujs.js

I am migrating from using the asset pipeline to webpacker in Rails 5.2. My AJAX responses are all causing Uncaught ReferenceError: $ is not defined in rails-ujs.js errors in the browser console.

I have setup my webpacker environment to include jquery.

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

environment.plugins.append("Provide", new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
  Popper: ['popper.js', 'default']
}));

module.exports = environment;

I have imported rails-ujs and turbolinks in my ../packs/application.js

import Rails from 'rails-ujs'
import 'activestorage'
import 'bootstrap'
...
import Turbolinks from "turbolinks"

Rails.start();
Turbolinks.start();

// Import application specific stuff
import 'application/javascripts'

I then try to add a class when the request is completed. similar to what is shown in the rails guides https://guides.rubyonrails.org/working_with_javascript_in_rails.html#server-side-concerns

My show.js.erb file looks like this

$("#result").addClass("active")

I get an error

Uncaught ReferenceError: $ is not defined
    at <anonymous>:1:1
    at processResponse (rails-ujs.js:282)
    at rails-ujs.js:195
    at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.js:263)
like image 710
TheRealNeil Avatar asked May 07 '19 11:05

TheRealNeil


2 Answers

In the meantime, I figured out what I had done wrong. I needed to configure an alias. I found the solution in the docs https://github.com/rails/webpacker/blob/master/docs/webpack.md#configuration

Adding environment.config.set('resolve.alias', {jquery: 'jquery/src/jquery'}); to my /config/webpacker/environment.js did the trick.

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

environment.plugins.append("Provide", new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
  Popper: ['popper.js', 'default']
}));

environment.config.set('resolve.alias', {jquery: 'jquery/src/jquery'});

module.exports = environment;
like image 99
TheRealNeil Avatar answered Nov 19 '22 09:11

TheRealNeil


Try in app/javascript/packs/application.js:

// jquery
import $ from 'jquery';
global.$ = $;
global.jQuery = $;

like image 31
Sahu Avatar answered Nov 19 '22 09:11

Sahu