How to use importmap to pin npm, yarn packages in Rails7?

8.2k views Asked by At

I am very excited to use Rails7 especially that we finally get rid of webpacker. However, today when I tried to try Rails7, I didn't get how to bundle javascript scripts anymore... and there wasn't tutorial there or I just could not find it.

For example, I wanted to import jquery so I ran

yarn add jquery

and then I wrote:

// application.js
//importmap-rails
import "@hotwired/turbo-rails"
import "controllers"
import jquery from 'jquery'

But it didn't work, then I read the readme on importmap-rails, and I ran

./bin/importmap pin jquery

then it added a line in config/importmap.rb

pin "jquery", to: "https://ga.jspm.io/npm:[email protected]/dist/jquery.js"

It worked, however, it was not what I expected exactly. I wanted the jquery came from node_modules/ instead of CDN

How can I achieve that? To import npm packages that I install from yarn/npm? Or just point out where I can find documents about how to use javascript in Rails7?

2

There are 2 answers

0
StevenHe On BEST ANSWER
./bin/importmap pin jquery --download

will download it.

Working with JavaScript in Rails (about dealing with JS but little info about importmap)

importmap-rails on GitHub (more info about importmap)

1
Joe Thor On

I believe you can manually update your config/importmap.rb file to read

pin "jquery", to: "./node_modules/jquery"

That being said, I believe the design decisions made with importmaps may not include npm or yarn. I believe importmaps represents an alternative method for handling javascript outside of webpacker/yarn/npm.