WICG / import-maps

How to control the behavior of JavaScript imports
https://html.spec.whatwg.org/multipage/webappapis.html#import-maps
Other
2.65k stars 69 forks source link

Unable to create folder alias to use in further alias. #291

Open trusktr opened 10 months ago

trusktr commented 10 months ago

For example, this

    <script type="importmap">
      {
        "imports": {
          "mods/": "../../../node_modules/",
          "@amazon-sumerian-hosts/core": "mods/@amazon-sumerian-hosts/core/src/core/index.js",
          "@amazon-sumerian-hosts/three": "mods/@amazon-sumerian-hosts/three/src/three.js/index.js"
        }
      }
    </script>

gives me these two warnings,

Ignored an import map value of "@amazon-sumerian-hosts/core": Bare specifier: mods/@amazon-sumerian-hosts/core/src/core/index.js
Ignored an import map value of "@amazon-sumerian-hosts/three": Bare specifier: mods/@amazon-sumerian-hosts/three/src/three.js/index.js

followed by this error:

Uncaught TypeError: Failed to resolve module specifier "@amazon-sumerian-hosts/three". Import Map: "@amazon-sumerian-hosts/three" matches with "@amazon-sumerian-hosts/three" but is blocked by a null value

I often find that I want to use a particular import map (copy/pasted from somewhere) and that sometimes the node_modules location is the only thing that changes. So I figured it would be easy to define where node_modules is a single time (to keep things more DRY) then re-use that location further on in the import map. In other words, when I copy/paste an import map to get something working in one project or other, I was trying to avoid having to modify many occurrences of ../../../node_modules/, and instead modify only one occurrence.

trusktr commented 10 months ago

Maybe the spec needs an update to allow aliasing withing the importmap itself? It seems like what I did should work, just the same was as the importmap modifies import specifiers in JS source code.

But if it isn't possible to allow this for some reason, then maybe a special syntax can be used? F.e.

    <script type="importmap">
      {
        "imports": {
          ":mods": "../../../node_modules/",
          "@amazon-sumerian-hosts/core": ":mods/@amazon-sumerian-hosts/core/src/core/index.js",
          "@amazon-sumerian-hosts/three": ":mods/@amazon-sumerian-hosts/three/src/three.js/index.js"
        }
      }
    </script>

in this example using a : symbol.

trusktr commented 10 months ago

Another reason this need pops up is writing HTML files in folders at different depths in the file system, where when you make a new file copied from another, you then need to update all the relative paths in the import map. I was trying to reduce it to a single modification instead of one per entry.

A current way to solve this is to make a <script modules="../../../node_modules"> or similar script that document.writes the importmap dynamically.