After hours of trial and error, this is the most effective way I found to properly set up Stimulus in an existing Rails 7 app using Importmap. If youβve run into issues like MIME type errors or Stimulus controllers not working, this should solve them.
β Step-by-Step Guide
1. Install Importmap (if not already installed)
bin/rails importmap:install
This command will:
- Set up
config/importmap.rb
- Create
app/javascript
and theapplication.js
file - Insert the correct tags into your layout
2. Install Turbo and Stimulus
bin/rails turbo:install stimulus:install
This will:
- Create the
controllers/
directory - Add a sample
hello_controller.js
- Register Stimulus with
application.js
- Pin everything properly in
importmap.rb
β Make Sure Your Layout Includes the Right Tags
In app/views/layouts/application.html.erb
, check that you have:
<%= javascript_importmap_tags %>
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
Do not use:
<!-- β Don't use this with importmap -->
<%= javascript_pack_tag "application" %>
β You're Done!
You should now have:
- No more MIME type errors
- Working Stimulus controllers
- Turbo ready if you want to use it
β¨ Bonus
Hereβs what a basic Stimulus controller looks like:
// app/javascript/controllers/hello_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static values = { name: String }
greet() {
alert(`Hello, ${this.nameValue}!`)
}
}
And how you use it in your view:
<div data-controller="hello" data-hello-name-value="World">
<button data-action="click->hello#greet">Greet</button>
</div>
Hope this helps someone save a few hours of head-scratching! π
Top comments (0)