trunk icon indicating copy to clipboard operation
trunk copied to clipboard

Proposal: Processing importmaps

Open ARogovskyy opened this issue 1 year ago • 1 comments

I currently need to import modules from JS snippets. This requires currently knowledge of the "final" (hash-appended) URL of the module. A similar problem occurs when using JS web workers, since those are loaded dynamically and not via a script-tag.

This is basically an addition to the current ongoing debate about having a "manifest" of all the files produced from trunk. I would like to propose a new feature that complements this.

Proposal

JS module importmaps allow you to assign almost arbitrary identifiers as aliases for modules, such that you can use these instead of full URLs. The idea would be to add a data-trunk attribute to these and let trunk replace the mapped URLs with the actual hashed output files. Taking the example from the MDN article, we would have something like

<script type="importmap" data-trunk>
  {
    "imports": {
      "square": "/square.js",
      "circle": "/circle.js"
    }
  }
</script>

This would be processed by trunk to something like

<script type="importmap">
  {
    "imports": {
      "square": "/square-HASH.js",
      "circle": "/circle-HASH.js"
    }
  }
</script>

Then, in both JS modules and JS snippets (which are modules as well), you can use the "well-known" module aliases to import:

import circle from "circle";

Pros of this approach:

  • Keeps up with trunk's tradition of using "vanilla" HTML as a file-index
  • Decouples the actual module from the URLs
  • Importmaps are well-defined JSON and not aribitrary JS, so it's easy to process

Cons / alternatives:

  • Does not solve the problem of referencing arbitrary assets (like images) from rust. Only works for modules
  • Alternative would be a full manifest. But this does not contradict this proposal; both can be simulatneously implemented.

Is this generally something that the maintainers consider useful / desirable? I wouldn't mind working on a PR if yes.

ARogovskyy avatar Feb 07 '24 19:02 ARogovskyy

I personally haven't work with importmaps so far. But it sounds like a reasonable improvement and it looks like you gave some though to it. I am working towards a 0.19.x release, so now would be the right time. I would welcome a PR on this.

ctron avatar Feb 08 '24 07:02 ctron