Module: Importmap::ImportmapTagsHelper

Defined in:
app/helpers/importmap/importmap_tags_helper.rb

Instance Method Summary collapse

Instance Method Details

#javascript_import_module_tag(*module_names) ⇒ Object

Import a named JavaScript module(s) using a script-module tag.



19
20
21
22
# File 'app/helpers/importmap/importmap_tags_helper.rb', line 19

def javascript_import_module_tag(*module_names)
  imports = Array(module_names).collect { |m| %(import "#{m}") }.join("\n")
  tag.script imports.html_safe, type: "module", nonce: request&.content_security_policy_nonce
end

#javascript_importmap_module_preload_tags(importmap = Rails.application.importmap, entry_point: "application") ⇒ Object

Link tags for preloading all modules marked as preload: true in the ‘importmap` (defaults to Rails.application.importmap), such that they’ll be fetched in advance by browsers supporting this link type (caniuse.com/?search=modulepreload).



27
28
29
30
31
# File 'app/helpers/importmap/importmap_tags_helper.rb', line 27

def javascript_importmap_module_preload_tags(importmap = Rails.application.importmap, entry_point: "application")
  packages = importmap.preloaded_module_packages(resolver: self, entry_point:, cache_key: entry_point)

  _generate_preload_tags(packages) { |path, package| [path, { integrity: package.integrity }] }
end

#javascript_importmap_tags(entry_point = "application", importmap: Rails.application.importmap) ⇒ Object

Setup all script tags needed to use an importmap-powered entrypoint (which defaults to application.js)



3
4
5
6
7
8
9
# File 'app/helpers/importmap/importmap_tags_helper.rb', line 3

def javascript_importmap_tags(entry_point = "application", importmap: Rails.application.importmap)
  safe_join [
    javascript_inline_importmap_tag(importmap.to_json(resolver: self)),
    javascript_importmap_module_preload_tags(importmap, entry_point:),
    javascript_import_module_tag(entry_point)
  ], "\n"
end

#javascript_inline_importmap_tag(importmap_json = Rails.application.importmap.to_json(resolver: self)) ⇒ Object

Generate an inline importmap tag using the passed ‘importmap_json` JSON string. By default, `Rails.application.importmap.to_json(resolver: self)` is used.



13
14
15
16
# File 'app/helpers/importmap/importmap_tags_helper.rb', line 13

def javascript_inline_importmap_tag(importmap_json = Rails.application.importmap.to_json(resolver: self))
  tag.script importmap_json.html_safe,
    type: "importmap", "data-turbo-track": "reload", nonce: request&.content_security_policy_nonce
end

#javascript_module_preload_tag(*paths) ⇒ Object

Link tag(s) for preloading the JavaScript module residing in ‘*paths`. Will return one link tag per path element.



34
35
36
# File 'app/helpers/importmap/importmap_tags_helper.rb', line 34

def javascript_module_preload_tag(*paths)
  _generate_preload_tags(paths) { |path| [path, {}] }
end