Skip to content

Add support for passing a custom importmap to the tag helper #187

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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