Import maps will improve cache busting
- Published at
- Updated at
- Reading time
- 2min
Have you heard of the new script type "importmap"? Import maps aren't listed in the MDN script element compatibility data yet, but according to caniuse.com, Chromium ships them, and Firefox implements them behind a feature flag.
Import maps will simplify frontend tooling. ๐ If you ship ES modules (ESM), the new script type enables you to rewrite ugly, complicated, and absolute file paths to file path identifiers.
<script type="importmap">
{
"imports": {
"dayjs": "https://cdn.skypack.dev/dayjs@1.10.7",
}
}
</script>
<script type="module">
import dayjs from 'dayjs';
// do stuff with 'dayjs'
</script>
But making imports easier to write isn't the only benefit of using import maps!
Ayooluwa Isaiah published a handy guide explaining import maps, and it includes a nice little tip that I haven't considered before.
Suppose you ship an ESM-based production app following all the best practices: your code is minified, bundled and code-splitted.
JavaScript files load other files, which then load more files. And, of course, you want to cache all files as long as possible, and that's why you ship hashed files (a-file
). With unique file names, you can cache all your files forever!
But there's one downside. Let's consider a dependencies tree resulting in this request waterfall.
main.982jda.js
|_ module.a93mwld.js
|_ dep.has83ks.js
All the files include hashed import
statements.
// main.js
import { module } from './module.a93mwld.js';
// module.js
import { dep } from './dep.has83ks.js';
What happens now when you update a dependency deep down in your module tree? All the file hashes change! ๐ฒ Even if all the other files are the same, a single dependency change invalidates all the file paths going up the dependency chain.
If, on the other hand, your files are based on import maps and identifiers, you can update a file path in a single location, and no other file needs to be touched.
<script type="importmap">
{
"imports": {
"main": "./main.982jda.js",
"module": "./module.a93mwld.js",
"dep": "./dep.has83ks.js"
}
}
</script>
There's no change when a dependency was updated! ๐ ๐
// main.js
import { module } from 'module';
// module.js
import { dep } from 'dep';
This is pretty sweet and I can't wait to see it in action!
Join 5.5k readers and learn something new every week with Web Weekly.