Skip to content

Commit e8682d5

Browse files
eliadhh
andauthored
Add support for passing a custom importmap to the tag helper (#187)
* 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. * Work around JSPM mysteriously returning 503 from CI This is meant to be temporary. * Update packager.rb Remove unrelated change --------- Co-authored-by: David Heinemeier Hansson <[email protected]>
1 parent 952f000 commit e8682d5

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

Diff for: app/helpers/importmap/importmap_tags_helper.rb

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
module Importmap::ImportmapTagsHelper
22
# Setup all script tags needed to use an importmap-powered entrypoint (which defaults to application.js)
3-
def javascript_importmap_tags(entry_point = "application", shim: true)
3+
def javascript_importmap_tags(entry_point = "application", shim: true, importmap: Rails.application.importmap)
44
safe_join [
5-
javascript_inline_importmap_tag,
6-
javascript_importmap_module_preload_tags,
5+
javascript_inline_importmap_tag(importmap.to_json(resolver: self)),
6+
javascript_importmap_module_preload_tags(importmap),
77
(javascript_importmap_shim_nonce_configuration_tag if shim),
88
(javascript_importmap_shim_tag if shim),
99
javascript_import_module_tag(entry_point)
@@ -34,7 +34,7 @@ def javascript_importmap_shim_tag(minimized: true)
3434
# Import a named JavaScript module(s) using a script-module tag.
3535
def javascript_import_module_tag(*module_names)
3636
imports = Array(module_names).collect { |m| %(import "#{m}") }.join("\n")
37-
tag.script imports.html_safe,
37+
tag.script imports.html_safe,
3838
type: "module", nonce: request&.content_security_policy_nonce
3939
end
4040

Diff for: test/importmap_tags_helper_test.rb

+14
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,18 @@ def content_security_policy_nonce
5555
ensure
5656
@request = nil
5757
end
58+
59+
test "using a custom importmap" do
60+
importmap = Importmap::Map.new
61+
importmap.pin "foo", preload: true
62+
importmap.pin "bar", preload: false
63+
importmap_html = javascript_importmap_tags("foo", importmap: importmap)
64+
65+
assert_includes importmap_html, %{<script type="importmap" data-turbo-track="reload">}
66+
assert_includes importmap_html, %{"foo": "/foo.js"}
67+
assert_includes importmap_html, %{"bar": "/bar.js"}
68+
assert_includes importmap_html, %{<link rel="modulepreload" href="/foo.js">}
69+
refute_includes importmap_html, %{<link rel="modulepreload" href="/bar.js">}
70+
assert_includes importmap_html, %{<script type="module">import "foo"</script>}
71+
end
5872
end

0 commit comments

Comments
 (0)