← Back

Propshaft - Serving static JS modules from libraries

Import maps allow developers to import JavaScript modules without the need to install them using npm or Yarn. This simplifies the project setup considerably and allows you to skip the installation of npm and NodeJS entirely.

Many web browser libraries, such as the Splide slideshow library require developers to include JS modules on their webpage. They usually instruct developers to first install the library with npm install @splidejs/splide and then import the library using an expression like import Splide from '@splidejs/splide';.

To enable import maps, make sure you install the importmap-rails gem:

./bin/bundle add importmap-rails
./bin/rails importmap:install

When using import maps, you no longer need to install the library, but instead embed it directly on your page. To add a library (for example Splide) to the import map, run the following command:

bin/importmap pin @splidejs/splide

This downloads the library and any additional requirements into the folder vendor/javascript and "pins" them in the import map config file in config/importmap.rb. All pinned libraries are automatically picked up if you generated your project with Rails 8.

If you upgraded from a previous version of Rails, make sure that the file

app/layouts/application.html.erb

contains the line

<%= javascript_importmap_tags %>

inside the <head> tag. This makes sure that all your pinned libraries from vendor/javascript are included in the page.

You can then use the libraries in both the main JS file app/javascript/application.js and any Stimulus controllers in app/javascript/controllers/*.js.

How to use in development

The importmaps gem generates the list of modules to import and injects them into app/layouts/application.html.erb. In development mode, Rails automatically serves them.
Note: if you change the pinned modules, you may need to restart the development server.

How to use in production

The importmaps gem generates the list of modules to import and injects them into app/layouts/application.html.erb. When precompiling the assets, Rails automatically places all files from the vendor folder in public/assets and serves them.