Rails 7 will no longer ship with webpacker by default but will instead use importmaps. This is a much lighter solution for applications which mostly rely on external scripts.

This post explains how to migrate an existing application from webpacker to importmaps.

Installation

Remove the webpacker gem from your Gemfile and add the importmap-rails gem instead. Next, remove the javascript_pack_tag line from your application layout in app/views/layouts/application.html.erb.

To set everything up, run the importmap installer with the command ./bin/rails importmap:install. This will generate a few new files for you:

  • config/importmap.rb: this file contains URLs to the libraries you use in your app, such as jQuery, Turbo or Stimulus.
  • app/javascript/application.js: this is the entrypoint for your JavaScript code. It is used to import libraries and to launch your JavaScript-Code.

Migrating custom code

With webpacker, your custom code used to live in app/javascript/packs/application.js. With importmaps, this changed to be app/javascript/application.js. You can move your custom code into the new file and delete the old pack file. Then, follow the instructions below for migrating the dependencies you use.

Migrating dependencies

With importmaps, you no longer list your dependencies in package.json, but instead they are automatically downloaded by the browser. To add dependencies to your importmap, run the following command:

./bin/importmap pin jquery

This will automatically insert the CDN-URL of jQuery into your importmap.

Iterate through the dependencies listed in package.json and add them to the importmap using the above command. Once you are done, you can delete package.json and the node_modules folder.

turbolinks has been replaced by Turbo, which is why we should migrate it as well. This migration is pretty easy.

First, remove the turbolinks gem from your Gemfile and replace it with turbo-rails. To set up Turbo, run ./bin/rails turbo:install.

This will automatically add turbo-rails to your importmap and will append the line

import "@hotwired/turbo-rails"

to your app/javascript/application.js. This is enough to load and start Turbo automatically.

The last change concerns the renaming of turbolinks to turbo: if you listened for the turbolinks:load event, you need to replace it with turbo:load. If you were using data-turbolinks attributes, you need to replace them with data-turbo.

You might also want to replace the event ajax:success with turbo:submit-end if you used it anywhere.

Migrating Stimulus

First, add stimulus-rails to your Gemfile. To set up Stimulus, run ./bin/rails stimulus:install.

This will automatically create the directory app/javascript/controllers containing an example controller, pin the Stimulus dependency in config/importmap.rb and import the controllers in app/javascript/application.js.

You can now move your Stimulus controllers to app/javascript/controllers where they are automatically loaded.