Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError: $ is not defined in Rails 6 jquery webpacker

I am using Rails 6.0.3.2, ruby 2.7.1, yarn 1.22.0.

I am trying to do normal UJS stuff, and this is the error I am getting:

VM125:1 Uncaught ReferenceError: $ is not defined
    at <anonymous>:1:1
    at processResponse (rails-ujs.js:283)
    at rails-ujs.js:196
    at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.js:264)

This is my package.json:

{
  "name": "myapp",
  "private": true,
  "dependencies": {
    "@rails/actioncable": "^6.0.0",
    "@rails/actiontext": "^6.0.2-2",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "4.2.2",
    "bootstrap": "^4.4.1",
    "data-confirm-modal": "^1.6.2",
    "expose-loader": "^1.0.0",
    "flickity": "^2.2.1",
    "jquery": "3.4.1",
    "local-time": "^2.1.0",
    "popper.js": "^1.16.1",
    "stimulus": "^1.1.1",
    "trix": "^1.0.0",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.10.3"
  }
}

This is my environment.js:

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

const webpack = require('webpack')
environment.plugins.append('Provide', new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
  Rails: '@rails/ujs'
}))

// environment.loaders.append('jquery', {
//     test: require.resolve('jquery'),
//     use: [{
//         loader: 'expose-loader',
//         options: '$',
//     }, {
//         loader: 'expose-loader',
//         options: 'jQuery',
//     }],
// });

module.exports = environment

As you can see from the commented out code above, I also tried using expose-loader per this answer but that gave me other errors.

In my application.js, I have the following:

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

import '../src/jquery.min'
.
.
.
import "controllers"

require("trix")
require("@rails/actiontext")

How do I fix this?

like image 659
marcamillion Avatar asked Jul 17 '20 02:07

marcamillion


1 Answers

Add below code in : app/javascript/packs/application.js

window.jQuery = $;
window.$ = $;

So jQuery keywords could be picked up.

like image 119
code_aks Avatar answered Oct 22 '22 04:10

code_aks