Open
Description
Importmaps are available in major browsers for two years already, and there is polyfill for older ones, which makes importmaps suitable for production.
There are 3 major types of importmap entries - URL, node module, and asset. While it's certainly possible to use importmaps in hugo, the way they are constructed from templates looks ugly.
Here is an example:
{{ $apline := (resources.Get "node_modules/dist/module.esm.min.js" | resources.Fingerprint).RelPermalink }}
{{ $app := (resources.Get "js/app.js" | resources.Minify | resources.Fingerprint).RelPermalink }}
<script type="importmap">
imports: {
{
"vue": "https://unpkg.com/[email protected]/dist/vue.esm-browser.prod.js",
"my-app": "{{ $app }}",
{{- range readDir "assets/js/components" -}}
{{ $res := resources.Get (print "js/components/" .Name) }}
"components/{{ substr .Name 0 -3 }}": "{{ ($res | resources.Minify | resources.Fingerprint).RelPermalink }}",
{{- end -}}
"alpinejs": "{{ $alpine }}"
}
}
</script>
<link rel="modulepreload" href="{{ $alpine }}"></link>
<link rel="modulepreload" href="{{ $app }}"></link>
Note that currently it seems impossible to import node module properly without using js.Build
, so they are in assets. There probably is a better way to generate an importmap, but anyway it would be nice to generate the code above with a config:
[importmap.vue]
url = "https://unpkg.com/[email protected]/dist/vue.esm-browser.prod.js"
[importmap.app]
asset = "js/app.js"
preload = true
[importmap.components]
dir = "js/components"
prefix = "components/"
[importmap.aplinejs]
node = "alpinejs"
preload = true
And then simply {{ .Site.Importmap }}
in a template.