Skip to content

Instantly share code, notes, and snippets.

@forsbergplustwo
Last active October 25, 2021 08:55
Show Gist options
  • Save forsbergplustwo/a0df51122d1a0cc1d10d9edb7199d08c to your computer and use it in GitHub Desktop.
Save forsbergplustwo/a0df51122d1a0cc1d10d9edb7199d08c to your computer and use it in GitHub Desktop.
Adding Javascript from a Rails Engine, using importmap-rails
# my_engine/my_engine.gemspec
spec.add_dependency "importmap-rails", "~> 0.7.6"
# my_engine/lib/my_engine.rb
require "importmap-rails"
# my_engine/lib/my_engine.rb
module MyEngine
class Engine < ::Rails::Engine
initializer "my_engine.importmap", after: "importmap" do |app|
app.importmap.draw(MyEngine::Engine.root.join("config/importmap.rb"))
end
initializer "my_engine.assets_and_hosts" do |app|
app.config.assets.paths << MyEngine::Engine.root.join("app", "assets", "javascripts")
app.config.assets.precompile += %w[
my_engine_javascript.js
]
end
end
end
# my_engine/config/importmap.rb
pin "my_engine_javascript", to: "my_engine_javascript.js"
// app/assets/javascripts/my_engine_javascript.js
export function hello(name) {
console.log(`Hello ${name}!`)
}
// APP (NOT ENGINE)
import { hello } from "my_engine_javascript"
hello("Engine")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment