Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add support for passing a custom importmap to the tag helper
This is a great feature whenever you have separate areas of the application with completely different sets of dependencies. The most common example of that is admin areas, both on the main Rails application or coming from engines.
  • Loading branch information
elia committed Jun 14, 2023
commit 4b06c2421d717896eed977d8f89282c69b038b2a
8 changes: 4 additions & 4 deletions app/helpers/importmap/importmap_tags_helper.rb
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
module Importmap::ImportmapTagsHelper
# Setup all script tags needed to use an importmap-powered entrypoint (which defaults to application.js)
def javascript_importmap_tags(entry_point = "application", shim: true)
def javascript_importmap_tags(entry_point = "application", shim: true, importmap: Rails.application.importmap)
safe_join [
javascript_inline_importmap_tag,
javascript_importmap_module_preload_tags,
javascript_inline_importmap_tag(importmap.to_json(resolver: self)),
javascript_importmap_module_preload_tags(importmap),
(javascript_importmap_shim_nonce_configuration_tag if shim),
(javascript_importmap_shim_tag if shim),
javascript_import_module_tag(entry_point)
Expand Down Expand Up @@ -34,7 +34,7 @@ def javascript_importmap_shim_tag(minimized: true)
# Import a named JavaScript module(s) using a script-module tag.
def javascript_import_module_tag(*module_names)
imports = Array(module_names).collect { |m| %(import "#{m}") }.join("\n")
tag.script imports.html_safe,
tag.script imports.html_safe,
type: "module", nonce: request&.content_security_policy_nonce
end

Expand Down
14 changes: 14 additions & 0 deletions test/importmap_tags_helper_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,18 @@ def content_security_policy_nonce
ensure
@request = nil
end

test "using a custom importmap" do
importmap = Importmap::Map.new
importmap.pin "foo", preload: true
importmap.pin "bar", preload: false
importmap_html = javascript_importmap_tags("foo", importmap: importmap)

assert_includes importmap_html, %{<script type="importmap" data-turbo-track="reload">}
assert_includes importmap_html, %{"foo": "/foo.js"}
assert_includes importmap_html, %{"bar": "/bar.js"}
assert_includes importmap_html, %{<link rel="modulepreload" href="/foo.js">}
refute_includes importmap_html, %{<link rel="modulepreload" href="/bar.js">}
assert_includes importmap_html, %{<script type="module">import "foo"</script>}
end
end