rails/jquery-rails

Rails 7 with importmap

mohloko opened this issue · 3 comments

How I can make it work?

I spent whole afternoon learned how to import jquery in Rails 7

edit in Gemfile and run bundle install

gem 'jquery-rails'

edit application.js

// app/javascript/application.js
// jquery
import 'jquery'
import 'jquery_ujs'

edit importmap.rb

# config/importmap.rb

pin "jquery", to: "jquery.min.js", preload: true
pin "jquery_ujs", to: "jquery_ujs.js", preload: true

edit config/initializers/assets.rb

# config/initializers/assets.rb


Rails.application.config.assets.precompile += %w( jquery.min.js jquery_ujs.js )

finally should work

and if you want a specific version of jQuery (2 or 3):

// app/javascript/application.js

import 'jquery'
import 'jquery_ujs'
# config/importmap.rb

pin "jquery", to: "jquery3.min.js", preload: true
pin "jquery_ujs", to: "jquery_ujs.js", preload: true
# config/initializers/assets.rb

Rails.application.config.assets.precompile += %w( jquery3.min.js jquery_ujs.js )
ArturT commented

The solution is working.

If you use Sprockets 4.x then it's recommended to use app/assets/config/manifest.js instead of Rails.application.config.assets.precompile.

# app/assets/config/manifest.js
//= link jquery.min.js
//= link jquery_ujs.js