Search code examples
jqueryruby-on-railsimport-maps

How can I install jQuery in Rails 7 with importmap?


I have a new Rails 7 application. I'm currently trying to learn all the new features since Rails 5. I want to use the following code in my javascript file, but so far I'm getting the following error: Uncaught ReferenceError: $ is not defined.

$(document).on("turbo:load", () => {
  console.log("turbo!");
});

Here are two other relevant files. If I need to post anything else please let me know.

importmap.rb

pin "application", preload: true
pin "jquery", to: "https://ga.jspm.io/npm:[email protected]/dist/jquery.js", preload: true
pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true
pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
pin "el-transition", to: "https://ga.jspm.io/npm:[email protected]/index.js"

pin_all_from "app/javascript/controllers", under: "controllers"

application.js

import "@hotwired/turbo-rails"
import "jquery"

$(document).on("turbo:load", () => {
  console.log("turbo!");
});

Solution

  • Just switch to CDN other than jspm, jQuery will be global on import:

    # config/importmap.rb
    
    # NOTE: pin jquery to jsdelivr instead of jspm
    pin "jquery", to: "https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.js"
    
    // app/javascript/application.js
    
    import "jquery"; // this import first
    import "script"; // then your other imports that use `$`
    
    // NOTE: don't use relative imports: `import "./script"`
    //       add `pin "script"` to `importmap.rb`
    
    console.log($); // ok
    
    // app/javascript/script.js
    
    console.log($)  // ok
    

    Everything just works, one import, multiple imports, jquery plugins. No extra hoisting needed.