DEV Community

Fadly Setiawan
Fadly Setiawan

Posted on

πŸš€ Installing Stimulus in an Existing Rails 7 Project (with Importmap)

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
Enter fullscreen mode Exit fullscreen mode

This command will:

  • Set up config/importmap.rb
  • Create app/javascript and the application.js file
  • Insert the correct tags into your layout

2. Install Turbo and Stimulus

bin/rails turbo:install stimulus:install
Enter fullscreen mode Exit fullscreen mode

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" %>
Enter fullscreen mode Exit fullscreen mode

Do not use:

<!-- ❌ Don't use this with importmap -->
<%= javascript_pack_tag "application" %>
Enter fullscreen mode Exit fullscreen mode

βœ… 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}!`)
  }
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Hope this helps someone save a few hours of head-scratching! πŸŽ‰

ACI image

ACI.dev: Best Open-Source Composio Alternative (AI Agent Tooling)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Star our GitHub!

Top comments (0)

ACI image

ACI.dev: Fully Open-source AI Agent Tool-Use Infra (Composio Alternative)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Check out our GitHub!