DEV Community

Morten Trolle
Morten Trolle

Posted on

Running StimulusJS & ImportMap with asset pipeline / Rails 6

I've never been a fan of Webpacker. So when starting a new project back in the Rails 5.1 days I avoided Webpacker and stuck to asset pipeline.

We have a ton of Coffeescript. And later on we upgraded to Rails 6.1, but stuck to our beloved asset pipeline.

Now Rails 7 is in front of us, but we are not quite ready to move to Rails 7 yet. But we wanna start taking advantage of StimulusJS and ImportMap and start slowly migrating our old Coffeescripts to ES6 and StimulusJS.

From the get go I tried converting to the full turbo suite, also upgrading Turbolinks 5 to the new Turbo. By the looks of it, it worked out great. But once I started to submit forms I realized we are far from ready to use Turbo.
With Turbo by default, Rails / Turbo will commit all forms with Ajax and Turbo will require your controllers to render http bad request on error and redirect with http status 303 (see other). But Rails renders default 302 (found) and then Turbo will try to handle that response instead of actually redirecting.

So we quickly gave up on Turbo. For now. That requires much more effort in our controllers than we were ready to do.

But back to the topic. Getting StimulusJS to work. I didn't care about ImportMap honestly, but StimulusJS does care. Either it's ImportMap or Webpacker and with that selection I had no doubt we needed ImportMap.

TL;DR

I updated my Gemfile to add:

# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev]
gem "stimulus-rails", '~> 1.2.1'
# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails]
gem "importmap-rails"
Enter fullscreen mode Exit fullscreen mode

I ran my bundle install and then installed ImportMap rails importmap:install
Finally I could run rails stimulus:install

Now in app/assets/config/manifest.js I added the lines:

//= link_tree ../../javascript .js
//= link_tree ../../../vendor/javascript .js
Enter fullscreen mode Exit fullscreen mode

Also very import, I renamed my app/assets/javascripts/application.js to app/assets/javascripts/gems.js to avoid naming conflicts with the new Stimulus created app/javascripts/application.js.

And finally in app/views/layouts/application.html.erb I removed

<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
Enter fullscreen mode Exit fullscreen mode

in favor of:

<%= javascript_include_tag 'gems', 'data-turbolinks-track': 'reload' %>
<%= javascript_importmap_tags %>
Enter fullscreen mode Exit fullscreen mode

Done.

Now I could run the mandetory test of creating my hello_controller.js and in a view add <div data-controller="hello"></div> and see my connect() method could write to the div innerText. Success!

Top comments (0)