Skip to content

Commit

Permalink
Add dynamic import maps example
Browse files Browse the repository at this point in the history
Closes #55.
  • Loading branch information
domenic committed Nov 9, 2018
1 parent 0ac124d commit 767b0f4
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,54 @@ See [the proto-spec](./spec.md) for more details on how this all works.

_What do we do in workers? Probably `new Worker(someURL, { type: "module", importMap: ... })`? Or should you set it from inside the worker? Should dedicated workers use their controlling document's map, either by default or always? Discuss in [#2](https://github.com/domenic/package-name-maps/issues/2)._

### Dynamic import map example

The above rules mean that you _can_ dynamically generate import maps, as long as you do so before performing any imports. For example:

```html
<script>
const im = document.createElement('script');
im.type = 'importmap';
im.textContent = JSON.stringify({
imports: {
'my-library': Math.random() ? '/my-awesome-library.mjs' : '/my-rad-library.mjs';
}
});
document.currentScript.after(im);
</script>

<script type="module">
import 'my-library';
</script>

A more realistic example might use this capability to override a previous import map based on feature detection:

```html
<script type="importmap">
{
"imports": {
"lodash": "/lodash.mjs",
"moment": "/moment.mjs"
}
}
</script>

<script>
if (!someFeatureDetection()) {
const im = document.createElement('script');
im.type = 'importmap';
im.textContent = '{ "imports": { "lodash": "/lodash-legacy-browsers.js" } }';
document.currentScript.after(im);
}
</script>

<script type="module">
import _ from "lodash"; // will get the right thing
</script>
```

Note that (like other `<script>` elements) modifying the contents of a `<script type="importmap">` after it's already inserted in the document will not work; this is why we wrote the above example by inserting a second `<script type="importmap">` to overwrite the first one.

### Scope

Import maps are an application-level thing, somewhat like service workers. (More formally, they would be per-module map, and thus per-realm.) They are not meant to be composed, but instead produced by a human or tool with a holistic view of your web application. For example, it would not make sense for a library to include a import map; libraries can simply reference modules by specifier, and let the application decide what URLs those specifiers map to.
Expand Down

0 comments on commit 767b0f4

Please sign in to comment.