Want more GoRails?

GoRails is packed full with 723 lessons just like this one.

Sign up to get full access or log in to your account and sit back.

Separate JavaScript Importmaps For Rails Engines

November 12, 2024

Track your progress

Sign in to track your progress and access subscription-only lessons.

Log In

Your Teacher

Hi, I'm Chris. I'm the creator of GoRails, Hatchbox.io and Jumpstart. I spend my time creating tutorials and tools to help Ruby on Rails developers build apps better and faster.

About This Episode

Rails engines often need a way of providing JavaScript for their views. We can do this using Importmaps regardless of what the application is using for assets.

Notes

Create a new Importmap::Map:

module MyEngine
  mattr_accessor :importmap, default: Importmap::Map.new
end

Pin imports

module MyEngine
  class Engine < ::Rails::Engine
    initializer "my_engine.importmap" do
      MyEngine.importmap.draw root.join("config/importmap.rb")
      MyEngine.importmap.cache_sweeper watches: root.join("app/javascript")

      ActiveSupport.on_load(:action_controller_base) do
        before_action { MyEngine.importmap.cache_sweeper.execute_if_updated }
      end
    end
  end
end

Render it in the view:

<%= javascript_importmap_tags "application", importmap: MyEngine.importmap %>

Want to stay up-to-date with Ruby on Rails?

Join 87,400+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.