Importmaps in Rails 7

Episode #312 by David Kimura

Summary

Import maps let you import JavaScript modules using logical names that map to versioned/digested files – directly from the browser. This will be a default in the upcoming Rails 7.
javascript rails 7.0 assets 8:14

Resources

Download Source Code

Summary

# Terminal
rails new template --skip-javascript
bundle add importmap-rails
bin/rails importmap:install
bundle add hotwire-rails
bin/rails hotwire:install
bin/importmap pin sortablejs
bin/importmap pin sortablejs --from jsdelivr

# config/importmap.rb
# Use Action Cable channels (remember to import "@rails/actionable" in your application.js)
# pin "@rails/actioncable", to: "actioncable.esm.js"
# pin_all_from "app/javascript/channels", under: "channels"

# Use direct uploads for Active Storage (remember to import "@rails/activestorage" in your application.js)
# pin "@rails/activestorage", to: "activestorage.esm.js"

# Use node modules from a JavaScript CDN by running ./bin/importmap

pin "application"
pin "@hotwired/stimulus", to: "stimulus.js"
pin "@hotwired/stimulus-importmap-autoloader", to: "stimulus-importmap-autoloader.js"
pin_all_from "app/javascript/controllers", under: "controllers"
pin "@hotwired/turbo-rails", to: "turbo.js"
pin "sortablejs", to: "https://cdn.jsdelivr.net/npm/[email protected]/modular/sortable.esm.js"

# app/javascript/controllers/position_controller.js
import { Controller } from "@hotwired/stimulus"
import Sortable from "sortablejs"
export default class extends Controller {

  connect() {
    this.sortable = Sortable.create(this.element, {
      animation: 150
    })
  }
}

# views/welcome/index.html.erb
<ul data-controller="position">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
</ul>

# views/layouts/application.html.erb
<%= javascript_importmap_tags %>