How to use Importmap on Rails 7

Rodrigo Souza
August 16, 2023

When Rails 7 was released, it came with super new goodies. Today we’ll talk about Importmap. Following the Rails guides description, Importmap is a JSPM tool (JavaScript Package Management) that allows you to use most NPM packages without the need for transpiling or bundling. You only need to import your JS modules by their name.

Applications using Importmap do not need Node.js or Yarn to function. If you plan to use Rails with importmap-rails to manage your JavaScript dependencies, there is no need to install Node.js or Yarn.

Importmap is automatically included on Rails 7 when you create your new application.

Adding JS modules

To add new packages to your application, run the bin/importmap pin command in your terminal:

$ bin/importmap pin jquery`

The command will include the CDN (Content Delivery Network) of the Jquery library to the config/importmap.rb file. To use it in your application, only import it on the application.js as per usual.

You can use a downloaded library installed in the vendor directory too! Only add the JS files in the vendor/javascript directory and pin it in config/importmap.rb.

Here’s an example for Bootstrap JS:

In the config/importmap.rb file:

pin "popper", to: 'popper.min.js', preload: true
pin "bootstrap", to: 'bootstrap.min.js', preload: true

In config/initializers/assets.rb file:

Rails.application.config.assets.precompile += %w( application.scss bootstrap.min.js popper.min.js )

Finally, in app/javascript/application.js:

import "popper"
import "bootstrap"

How do you decide between Importmap or another JS bundler?

The best approach when choosing between Importmap or another JS bundler, is to consider your Rails application requirements. As we mentioned before, Importmap was defined as the default option when you’re creating a new Rails 7 application, so if you will likely rely on Hotwire/Turbo/Stimulus, Importmap is a very good option for the long term. However, if your application has other requirements like JSX or Typescript (transpilation step) or tree-shaking, you’ll need to use other JSPM (Webpacker, js-bundling).

That’s it for today!

reinteractive is here to answer any questions you may have about your application. You can Contact Us here at any time.