Liz
Liz

Reputation: 1437

Rails 7 Jquery Not Working (Uncaught ReferenceError: $ is not defined)

I have a Rails 7 app setup (without Turbo) but with Bootstrap and Jquery. The jquery is showing up in my sources tab under assets, but I'm still getting an error saying "Uncaught ReferenceError: $ is not defined" whenever I try to use jquery.

A sample instance where this error appears is this code, on the $ before document:

  <script>
    $( document ).ready(function() {
        $('.sortable').railsSortable();
    });
  </script>

This error goes away if I add jquery via a CDN on my application.html.erb like this:

<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>

....however that then starts producing all the weird errors you get when JQuery is present twice.

I have the following in my application.js:

import "controllers"
import "jquery"
import "jquery_ujs"
import "popper"
import "bootstrap"
import "trix"
import "@rails/actiontext"

//= require jquery-ui
//= require rails_sortable
//= require activestorage
//= require font_awesome5

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

Here's my config/importmap.rb:

pin "application", preload: true
pin_all_from "app/javascript/controllers", under: "controllers"
pin "jquery", to: "jquery.min.js", preload: true
pin "jquery_ujs", to: "jquery_ujs.js", preload: true
pin "popper", to: "popper.js", preload: true
pin "bootstrap", to: "bootstrap.min.js", preload: true
pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
pin "trix"
pin "@rails/actiontext", to: "actiontext.js"

And here is my application.html.erb head section:

 <head>
    ...
    <%= if content_for?(:head) then yield(:head) end %>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag "application" %>
    <%= javascript_importmap_tags %>
    <%= include_gon %>
    <meta name="viewport" content="width=device-width, initial-scale=1">

  </head>

Can anyone see why this isn't working? I know there's no error in the JQuery script itself (because the error is called on any $), but I can't see why the JQuery that shows in the sources tab isn't being recognized.

Upvotes: 5

Views: 3217

Answers (1)

kevinluo201
kevinluo201

Reputation: 1663

If you only need to use jQuery, change like this

import jquery from "jquery"
window.$ = jquery
window.jQuery = jquery

However, if you want to use jQuery-UI, too You need a workaround by creating a file to include the 3 lines above.

// ./src/jquery.js
import jquery from "jquery"
window.$ = jquery
window.jQuery = jquery

And then in application.js

import "./src/jquery"
import "jquery-ui"

This solution is actually from GoRails :D

https://gorails.com/episodes/how-to-use-jquery-with-esbuild

Upvotes: 1

Related Questions