
Shipping in Chrome 89 are Import Maps, which allows control over what URLs get fetched when importing modules.
Let’s take a look at this very welcome addition.
When importing ES Modules (on the web), you need to refer to them using their full filenames or URLs:
import moment from "/js/moment/moment.js";
import { partition } from "/js/lodash-es/lodash.js";
In a Node environment however, you would write the snippet above as follows:
import moment from "moment";
import { partition } from "lodash";
(Node will map things to the /node_modules folder all by itself)
👉 So depending on where you run your code, your import statements need to change. Meh.
~
Thankfully Import Maps provide a solution to this. They allow you to specify which file/URL should be loaded when importing a package.
{
"imports": {
"moment": "/js/moment/moment.js",
"lodash": "/js/lodash-es/lodash.js"
}
}
With this in place the browser can handle import { partition } from "lodash" just fine, as it will load the file /js/lodash-es/lodash.js. 🎉
💡 With services like Skypack in place I can already imagine new tools will pop up which would automate the generation of such an import map based on a package[-lock].json that you feed it.
~
An import map is a tad of JSON file which you need to put it in a script[type="importmap"] element:
<script type="importmap">
{
"imports": {
"moment": "/js/moment/moment.js",
"lodash": "/js/lodash-es/lodash.js"
}
}
</script>
☝️ In the future it’ll also be possible to to put your import map into an external file and load it by specifying an src
<script type="importmap" src="import-map.importmap"></script>
To play nice with Content-Security Policy (CSP) the server needs to send the proper MIME-type though:
application/importmap+json
For more advanced usage, it’s also possible to add scoping.
~
These Import Maps sure are a very welcome addition. Unfortunately browser support is currently limited to Chrome only.
Update 2021.09.13: There’s a polyfill available for browsers that don’t support Import Maps: es-module-shims.
💡 Shown above is a dynamic CanIUse.com image, showing an always up-to-date support table. By the time you are reading this browser support might have become better.
Let’s hope other browsers follow suit soon. Relevant bugs to track:
- Safari: https://bugs.webkit.org/show_bug.cgi?id=220823
- Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=1688879
~
To help spread the contents of this post, feel free to retweet its announcement tweet:
Control the behavior of JavaScript imports with Import Maps
🏷 #EsModules #import #javascript pic.twitter.com/ZrzakJQ4tn
— Bram.us (@bramusblog) March 3, 2021
~
Thank me with a coffee.
I don’t do this for profit but a small one-time donation would surely put a smile on my face. Thanks!
To stay in the loop you can follow bramus on Bluesky or subscribe to the RSS feed.
Seems, the browser needs to load the import map befory any resolution of import URLs