Skip to content

Commit 828c2f3

Browse files
committed
Load legacy assets if dynamic modules are not supported
1 parent 1d48273 commit 828c2f3

File tree

1 file changed

+21
-5
lines changed

1 file changed

+21
-5
lines changed

vite_plugin_legacy/lib/vite_plugin_legacy/tag_helpers.rb

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,22 +9,38 @@ def vite_legacy_javascript_tag(name, asset_type: :javascript)
99

1010
legacy_name = name.sub(/(\..+)|$/, '-legacy\1')
1111
import_tag = content_tag(:script, nomodule: true) {
12-
"System.import('#{ vite_asset_path(legacy_name, type: asset_type) }')".html_safe
12+
vite_legacy_import_body(name, asset_type: asset_type)
1313
}
1414

15-
safe_join [vite_legacy_polyfill_tag, import_tag]
15+
import_tag
1616
end
1717

1818
# Public: Same as `vite_legacy_javascript_tag`, but for TypeScript entries.
1919
def vite_legacy_typescript_tag(name)
2020
vite_legacy_javascript_tag(name, asset_type: :typescript)
2121
end
2222

23-
# Internal: Renders the vite-legacy-polyfill to enable code splitting in
23+
# Renders the vite-legacy-polyfill to enable code splitting in
2424
# browsers that do not support modules.
25-
def vite_legacy_polyfill_tag
25+
# Entrypoints in format: {"entrypoint_name" => asset_type }
26+
# e.g.: { "application" => :typescript }
27+
def vite_legacy_polyfill_tag(entrypoints)
2628
return if ViteRuby.instance.dev_server_running?
2729

28-
content_tag(:script, nil, nomodule: true, id: 'vite-legacy-polyfill', src: vite_asset_path('legacy-polyfills', type: :virtual))
30+
tags = []
31+
tags.push(content_tag(:script, nil, nomodule: true, id: 'vite-legacy-polyfill', src: vite_asset_path('legacy-polyfills', type: :virtual)))
32+
entrypoints.each do |entrypoint, asset_type|
33+
tags.push(content_tag(:script, nil, type: 'module') { vite_dynamic_fallback_inline_code(entrypoint, asset_type: asset_type) })
34+
end
35+
safe_join(tags, "\n")
36+
end
37+
38+
def vite_dynamic_fallback_inline_code(name, asset_type: :javascript)
39+
%Q{!function(){try{new Function("m","return import(m)")}catch(o){console.warn("vite: loading legacy build because dynamic import is unsupported, syntax error above should be ignored");var e=document.getElementById("vite-legacy-polyfill"),n=document.createElement("script");n.src=e.src,n.onload=function(){#{vite_legacy_import_body(name, asset_type: asset_type)}},document.body.appendChild(n)}}();}.html_safe
40+
end
41+
42+
def vite_legacy_import_body(name, asset_type: :javascript)
43+
legacy_name = name.sub(/(\..+)|$/, '-legacy\1')
44+
"System.import('#{ vite_asset_path(legacy_name, type: asset_type) }')".html_safe
2945
end
3046
end

0 commit comments

Comments
 (0)