Skip to content
This repository was archived by the owner on Feb 26, 2025. It is now read-only.
This repository was archived by the owner on Feb 26, 2025. It is now read-only.

How do we install import maps in worker/worklet contexts? #2

Open

Description

@domenic

It's unclear how to apply import maps to a worker. There are essentially three categories of approach I can think of:

  • The worker-creator specifies the import map, e.g. with new Worker(url, { type: "module", importMap: ... })
  • The worker itself specifies the import map, e.g. with self.setImportMap(...) or import "map.json" assert { type: "importmap" }.
  • The HTTP headers on the worker script specify the import map, e.g. Import-Map: file.json or maybe even Import-Map: { ... a bunch of JSON inlined into the header ... }.

The worker-creator specified import map is a bit strange:

  • It's unlike the Window-context mechanism in that the creator of the realm controls the realm's module resolution, instead of the realm itself
  • It's like the Window-context mechanism in that the script that runs in the realm does not control the realm's module resolution; the control is external to the script itself.

Basically, there is no clear translation of <script type="importmap"> into a worker setting.

Also, as pointed out below, anything where the creator controls the import map works poorly for service worker updates.

The worker itself specifying seems basically unworkable, for reasons discussed below.

And the header-based mechanism is hard to develop against and deploy.

Original post, for posterity, including references to the old "package name map" name

We have a sketch of an idea for how to supply a package name map to a worker:

new Worker(someURL, { type: "module", packageMap: ... });

This is interesting to contrast with the mechanism for window contexts proposed currently (and discussed in #1):

  • It's unlike the Window-context mechanism in that the creator of the realm controls the realm's module resolution, instead of the realm itself
  • It's like the Window-context mechanism in that the script that runs in the realm does not control the realm's module resolution; the control is external to the script itself.

Basically, there is no clear translation of <script type="packagemap"> into a worker setting.

If we went with this, presumably we'd do the same for SharedWorker. Service workers would probably use an option to navigator.serviceWorker.register(), and have an impact similar to the other options?

For worklets, I guess you'd do something like CSS.paintWorklet.setModuleMap({ ... }). Only callable once, of course.

In all cases, it would be nice to make it easy to inherit a package name map. With the current tentative proposal you could do

new Worker(url, {
  type: "module",
  packageMap: JSON.parse(document.querySelector('script[type="packagemap"]').textContent)
});

but this is fairly verbose and a bit wasteful (since the browser has already done all the parsing and processing of the map, and you're making it do that over again). At the same time, inheriting by default seems conceptually weird, since workers are a separate realm.

Activity

  1. matthewp commented on Mar 15, 2018

    @matthewp

    Could the packagemap script have a property on it, packageMap or something so you could use: document.querySelector('#mymap').packageMap to get it? Not sure if there is precedent for properties on elements only when it's a certain type like this.

  2. justinfagnani commented on Mar 15, 2018

    @justinfagnani
    Collaborator

    @matthewp I'd certainly like to see a .module property for <script type=module> that's a Promise resolving to the module object. If this ends up being a general feature, maybe we just need a .content or .value property. edit: those are bad names, because they don't imply them being the post-parse/instantiate object

  3. domenic commented on Mar 15, 2018

    @domenic
    CollaboratorAuthor

    Yeah, that seems pretty reasonable. I think I like the idea of a general property, with some name or another.

  4. guybedford commented on Aug 20, 2018

    @guybedford
    Collaborator

    Could we by default just have workers inherit the package map from the parent window?

    That seems to cover the 99% scenario.

    Isolation doesn't seem to align with the worker boundary, as much as it does concepts of Realms.

    I understand the issues for worklets and service workers but I'm' not sure they should be dominating use cases here.

  5. domenic commented on Aug 21, 2018

    @domenic
    CollaboratorAuthor

    Hmm, I don't understand. Workers don't share the parent realm so if you're saying isolation is aligned with realms then it is also aligned with the worker boundary.

  6. guybedford commented on Aug 21, 2018

    @guybedford
    Collaborator

    I was referring to the proposal to create isolated realms, but it's a somewhat misleading tangent.

    The question really is what is the use case for having a different package map for the worker, that couldn't be shared with the page?

  7. guybedford commented on Aug 22, 2018

    @guybedford
    Collaborator

    Note if we first shipped with the default of having the worker share the package map, then a future proposal could always provide package map isolation. The isolation picture and use cases will be clearer then than they are now to spec something good as necessary, and realms are possibly part of that picture too.

  8. domenic commented on Aug 22, 2018

    @domenic
    CollaboratorAuthor

    In the end I am very uncomfortable with sharing module-related features cross-realm. In general cross-realm sharing of state of this sort is largely unprecedented, and I'd be especially unhappy about doing it for modules, which right now are purely tied to realms.

    I am pretty certain that v0 will not have such a strange new feature as cross-realm sharing, even if we eventually want to introduce an easy way to do so.

  9. guybedford commented on Aug 22, 2018

    @guybedford
    Collaborator

    @domenic then we must guarantee that when it comes to implementations of the Realms proposal, that they do not share the package map with the main page by default.

  10. guybedford commented on Aug 22, 2018

    @guybedford
    Collaborator

    Also, note that what I'm suggesting here is a default behaviour - there is nothing to say this cannot be overridden.

    As someone who has worked on build tools in JS for a while, assuming all workers are instantiated with a packagemap argument will be a tooling nightmare - the third-party worker story is really being neglected from all directions currently which is incredibly worrying already.

  11. guybedford commented on Aug 22, 2018

    @guybedford
    Collaborator

    I see this is already catered to in the Realms spec (although interesting the Realms spec then effectively hinges on a full blown module API for modules support - tc39/proposal-shadowrealm#103).

    Passing the package map can work - we'd likely have build workflows that inject it into the new Worker instantiations, while npm packages leave it out. It's just annoying to have non-portable ties on this boundary effectively requiring a build step for third-party libraries with worker instantiations.

  12. domenic commented on Aug 22, 2018

    @domenic
    CollaboratorAuthor

    Yes, in general the realms proposal has a large variety of blocking issues on how it interacts with how browsers work with realms.

    I understand that breaking the current model for how realms work can be convenient, especially for tools or similar. I don't think that means we should do so, especially by default.

  13. guybedford commented on Aug 22, 2018

    @guybedford
    Collaborator

    Then make it a boolean option - packageMap: 'parent' and at least provide a portable-non build workflow for the web that can deal with workers. It's the complete lack of concern for portable worker workflows that gets me here. Us build tool authors then have to fix the problems you create here.

  14. domenic commented on Aug 22, 2018

    @domenic
    CollaboratorAuthor

    That's an idea. I'd prefer we have a more holistic story for how workers relate to other realms, instead of creating a one-off feature in package name maps. For example it's not clear why a package name map would be easily inherited but not a module map, or URL, or content security policy, or...

  15. domenic commented on Nov 2, 2018

    @domenic
    CollaboratorAuthor
  16. 39 remaining items

  17. fuweichin commented on Aug 19, 2022

    @fuweichin

    According to the import-map-processing section:

    Because they affect all imports, any import maps must be present and successfully fetched before any module resolution is done. This means that module graph fetching is blocked on import map fetching.

    This means that the inline form of import maps is strongly recommended for best performance.

    and given the fact that

    External import maps are not yet supported.

    Multiple import maps are not yet supported. https://crbug.com/927119

    I prefer the first approach, and my idea is to add an option "importMap" to WorkerOptions, as defined below

    dictionary WorkerOptions {
      WorkerType type = "classic";
      RequestCredentials credentials = "same-origin"; // credentials is only used if type is "module"
      DOMString name = "";
      ImportMapOptions importMap = null; // importMap is only used if type is "module"
    };
    
    dictionary ImportMapOptions {
      USVString src = ""; // a http/https url, a data url, or a blob url
      Blob srcObject = null; // option `importMap.src` takes precedence over `importMap.srcObject` if both specified
    };

    See also IDL of the Worker interface

    Notes:

    • Option importMap.src may not be supported until feature "external import maps" gets supported
    • Use of importMap.srcObject is strongly recommended for best performance

    Examples:

    You can dynamically generate import maps,

    let importMapObject = {
      imports: {
        a: './a.js'
      }
    };
    
    let worker = new Worker('path/to/worker.js', {
      type: 'module',
      importMap: {
        srcObject: new Blob([JSON.stringify(importMapObject)], {type: 'application/importmap+json'}),
      },
    });

    load an importmap resource manually,

    let importMapObject = await fetch('path/to/importmap.json').then((res) => {
      if (!res.ok) {
        throw new Error('Error loading importmap, received status: ' + res.status);
      }
      let type = res.headers.get('content-type');
      if (!/^application\/(importmap\+)?json/.test(type)) {
        console.warn('Resource interpreted as importmap but transferred with MIME type ' + type);
      }
      return res.blob();
    });
    
    let worker = new Worker('path/to/worker.js', {
      type: 'module',
      importMap: {
        srcObject: importMapObject,
      },
    });

    or use embed data url as importmap source until someday <script type="importmap" src="xxx"> is supported

    let worker = new Worker('path/to/worker.js', {
      type: 'module',
      importMap: {
        src: "data:application/importmap+json;base64,...",
      },
    });

    About multiple import maps

    If you do have multiple import maps to be used, then you may load multiple import maps from multiple sources, parse them into plain JSON objects, and merge them as single Blob, just do it by your self.

  18. jakearchibald commented on Aug 19, 2022

    @jakearchibald

    I don't think it needs to be that complicated. Just:

    const worker = new Worker(src, {
      type: 'module',
      importMap: {…}
    });

    Then, if folks want to fetch the import map from somewhere external, they can use fetch(). If they want to inherit the import map, they can get it from something like import.meta.importMap.

    For shared/service workers, where the worker creation may have been triggered by another environment, the import map is specified in a header.

  19. bartlomieju commented on Dec 11, 2022

    @bartlomieju
    Contributor

    I'm a bit late to the discussion and I already see there are a few folks from the Deno community here suggesting solutions and I wanted to give my 2 cents. The Deno team certainly recognizes that this is a requested feature that could help to solve many common workloads. I also recognize that our restrictions are in some places wildly different than in browsers - we don't need to consider import maps loaded via <script> tag.

    I don't think it needs to be that complicated. Just:

    const worker = new Worker(src, {
      type: 'module',
      importMap: {…}
    });

    Then, if folks want to fetch the import map from somewhere external, they can use fetch(). If they want to inherit the import map, they can get it from something like import.meta.importMap.

    For shared/service workers, where the worker creation may have been triggered by another environment, the import map is specified in a header.

    I agree with Jake here - but would really love to see a complementary option to specify a URL. In Deno's case a call to fetch() API requires a permission granted on the CLI via --allow-net flag; if we had a statically analyzable solution (with importMapUrl) then the permission check wouldn't be necessary; user aknowledgles that it's a part of their program and these sources are to be trusted.

    That said, I think it's more important to ship a first iteration of the support to get further discussion going and the Deno team is willing to dedicate resources to ship the first implementation on the agreed proposal in a one-month timeframe.

  20. AXT-AyaKoto commented on Jan 30, 2024

    @AXT-AyaKoto

    (Does this discussion allow me to join? Sorry if I overlooked some rules.)
    What is the current status of this issue?
    I can't write it well, but I want this.

    I want it to be as easy as possible.

    I don't think it needs to be that complicated. Just:

    const worker = new Worker(src, {
      type: 'module',
      importMap: {…}
    });

    I agree with Jake here - but would really love to see a complementary option to specify a URL. In Deno's case a call to fetch() API requires a permission granted on the CLI via --allow-net flag; if we had a statically analyzable solution (with importMapUrl) then the permission check wouldn't be necessary; user aknowledgles that it's a part of their program and these sources are to be trusted.

    It seems to me that you can just set a rule like "We can use either one, but importMap takes precedence."
    (Or is it possible to change the interpretation depending on the data type of importmap?)

  21. FoxLisk commented on Feb 5, 2024

    @FoxLisk

    This is a huge missing feature. I just went through a bunch of trouble to get all my import map stuff working properly to work around some oddities in how some libraries reference dependencies in their import statements, and then when moving to web workers it just doesn't work at all and I need a whole different solution and in fact probably just can't use modules at all.

  22. khrome commented on Feb 22, 2024

    @khrome

    I'm working on a module which uses a pluggable terrain loader in a worker as well as buildless ESM. I worked around the existing behavior using local links, but quickly realized, when importing it into app space, that I wouldn't be able to import any dependencies because they use named modules. This was just unacceptable, so I took the performance hit to proxy an iframe as a worker so I could inject an importmap into it. So far this is working well (though much more taxing than a worker would be).

    This is what I did to make that work: https://github.com/environment-safe/esm-worker/blob/master/src/index.mjs#L10-L59 (abandon all hope ye who enter). Feel free to crib the code or use the module.

    Here's hoping it doesn't take another 5 years to land this as a native feature. 🤞

  23. JoakimCh commented on Mar 7, 2024

    @JoakimCh

    Please just apply the import map to anything which can import a module (it's called an "import map" for a reason guys!!).

    It's beyond ridiculous in my opinion that we are in 2024 and we're still discussing this. My worklets and workers doesn't function because of this stupidity. A terrible developer experience!

    Anything but what I suggested IS a terrible developer experience and there are no GOOD arguments against it really.

    6 years discussing this... It's a shame.

  24. jespertheend commented on Mar 8, 2024

    @jespertheend

    I don't think the discussions is what's delaying it here. I think it is because no browser vendor has the capacity to work on it.

  25. rektide commented on Jun 4, 2024

    @rektide

    To Domenic's original proposal here, just as a module has a .type on it's object exposing that attribute, it would be really cool if there was a programmatic interface to import maps attrobutes that webdevs could talk to. 👍 to a hypothetical .importMaps or what have you.

    But boy oh boy am I happy to take whatever I can get here! Fine if this is implicit; I really just want anything, badly.

    Is anyone successfully working around by deploying a https://github.com/joeldenning/import-map-service-worker serviceworker or some other translator?

  26. kungfooman commented on Jul 18, 2024

    @kungfooman

    What about relative import map paths, would they always resolve against document.baseURI (or whatever the browser internal way is to resolve relative import map paths) or should that be an option?

    Simple example of relative paths:

            <script type="importmap">{"imports": {
                "esm-worker": "../src/index.js",
                "calculator": "./calculator.js"
            }}</script>
  27. AshleyScirra commented on Sep 13, 2024

    @AshleyScirra

    We just ran in to this with Construct - we added support for import maps, but our engine supports running in both DOM and worker contexts, and import maps only work in the DOM context. For us it's a configurable option so users can work around by using DOM context, but there are some nice performance benefits to running everything in a web worker, so it's a shame this isn't supported by import maps yet.

    FWIW, I saw that there's a proposal for dynamic import maps - see also #92. If browsers support dynamically loading import maps rather than only one specified up-front, then it seems this potentially opens the way to an API, e.g. self.addImportMap(...), which could be supported in both the DOM and workers. This then provides at least some way to load import maps in workers - e.g. you could load bootstrap.js in a worker with code along the lines of:

    await self.addImportMap(...);
    await import("./main.js");

    ...and then main.js loads as a module in the worker with the import map specified. Perhaps not ideal and a few roundtrips to the network, but it would get the job done until other questions around how to specify an import map up-front are resolved, and even once they are, presumably the ability to have dynamic import maps in workers would still be useful for the same reasons it's useful in the DOM context.

  28. WebReflection commented on Feb 6, 2025

    @WebReflection

    I had similar thoughts about this pattern:

    The worker-creator specifies the import map, e.g. with new Worker(url, { type: "module", importMap: ... })

    I have also read all concerns around module resolutions and everything but I think that:

    • the worker creator already defines the kind of code the worker runs via type, the worker incapable of defining itself as module has never been a concern so I wonder if we could relax around an extra importMap field as that looks just simple/practical enough
    • SharedWorker and Worker already have different options field, i.e. name, and so it does the ServiceWorker. The latter one seems to be the only problematic though so ... couldn't we just move forward with a field that works only in Worker constructor and maybe SharedWorker too?

    I would appreciate an inherit or parent convention too because it's usually on the main thread that things get defined via importmap, it's also usually inline or it could even be at runtime. Having the ability to pass that definition down workers or shared workers that must be part of the same origin feels natural to me, while being incapable of using importmap on modules within workers feels super weird and I couldn't imagine we are still without a solution after almost 7 years, reason I've opened a new issue in WHTWG where I could not find anything related, I didn't think about this space.

    Workers and SharedWorkers are used more and more these days, also created dynamically via Blob, having importmaps pre-defined in there would just be plain awesome and it helps making code more portable without needing at all costs CDNs and with the ability to update modules once on the main thread and nowhere else.

    Thanks for trying to move this forward in any way or shape, current polyfills do too much and are not natural or great in practice but kinda inevitable if nothing else happens.

  29. trusktr commented on Feb 15, 2025

    @trusktr

    I was thinking the following seemed obvious, and then I saw @kungfooman's similar comment #2 (comment). Is there something not doable with the following?

    <script type="module">
    {
      "imports": {
        "some-library": "https://example.com/some-library.js"
      },
      "scopes": {
        "/serviceworker.js": {
          "imports": {
            "another-library": "https://example.com/another-library.js"
          },
        },
        "/my-regular-worker.js": {
          "imports": {
            "other-library": "https://example.com/other-library.js"
          },
        },
      }
    }
    </script>
    
    <script type="module">
      import {whatever} from 'some-library'
    
      whatever()
    
      navigator.serviceWorker.register('/serviceworker.js', { type: 'module' })
    
      new Worker('/my-regular-worker.js', { type: 'module' })
    </script>
    // /serviceworker.js
    import {something} from 'another-library'
    
    something()
    // /my-regular-worker.js
    import {other} from 'other-library'
    
    other()

    It follows the same mantra of @oscarotero's #2 (comment)

    <script type="importmap">...</script>
    
    <script type="module">...</script>
    <script type="module">...</script>
    <script type="module">...</script>

    in that everything about the app imports is known up front, then everything else runs (worker or not).

    Thie idea is also intuitive with @WebReflection's sentiment that it makes sense for it all to be inherited from the main context.

    We could still add an alternative API later, like new Worker('..', {..., importMap: {...}}) or some sort of self-registration, which could override the one from the <script type=importmap> of the parent.

    Any problem with this?

  30. WebReflection commented on Feb 15, 2025

    @WebReflection

    for what is worth it, I wouldn't mind @trusktr proposal neither, as long as there is one place to define import maps and, when any Worker like is bootstrapped as module, the only case this feature makes sense, we could inherit from that main thread/creator definition.

    This is probably even better than an importMap field because while it works with Dynamic Workers, it's a can of worms with SharedWorkers as branching out different importMap per same SharedWorker end point feels like a huge slippery slope to disasters ... so let's keep the workers free from any related burden, provide a way to define their resolutions in one single place (main thread) and let them resolve through their trusted creator when names are not canonical/asbolute URLs ???

    edit in case it needs disambiguation, that could be importMap: 'inherit' as option field, so what's broken today will still be broken, what's optin-in to this new field will inherit the creator thread definition and that can work down the Worker in Worker use case too.

  31. guybedford commented on Feb 15, 2025

    @guybedford
    Collaborator

    @nicolo-ribaudo has a PR up to add the import map option support to workers to resolve this issue, both supporting an explicit map and an inherits option currently - whatwg/html#10858. Further feedback / support there is very welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions