Sunday, May 19, 2024
HomeJavaScriptImport maps will enhance cache busting

Import maps will enhance cache busting


Have you ever heard of the brand new script sort “importmap”? Import maps aren’t listed in the MDN script component compatibility information but, however in line with caniuse.com, Chromium ships them, and Firefox implements them behind a function flag.

Caniuse importmap support table

Import maps will simplify frontend tooling. 🎉 In the event you ship ES modules (ESM), the brand new script sort lets you rewrite ugly, difficult, and absolute file paths to file path identifiers.

<script sort="importmap">
{
  "imports": {
    "dayjs": "https://cdn.skypack.dev/dayjs@1.10.7",
  }
}
</script>
<script sort="module">
  import dayjs from 'dayjs';

  
</script>

However making imports simpler to jot down is not the one advantage of utilizing import maps!

Import maps allow longer cache length

Ayooluwa Isaiah revealed a helpful information explaining import maps, and it features a good little tip that I have not thought of earlier than.

Suppose you ship an ESM-based manufacturing app following all the very best practices: your code is minified, bundled and code-splitted.

JavaScript information load different information, which then load extra information. And, after all, you wish to cache all information so long as attainable, and that is why you ship hashed information (a-file.affsd892mds.js). With distinctive file names, you may cache all of your information eternally!

However there’s one draw back. Let’s think about a dependencies tree ensuing on this request waterfall.

foremost.982jda.js
|_ module.a93mwld.js
   |_ dep.has83ks.js

All of the information embrace hashed import statements.


import { module } from './module.a93mwld.js';


import { dep } from './dep.has83ks.js';

What occurs now while you replace a dependency deep down in your module tree? All of the file hashes change! 😲 Even when all the opposite information are the identical, a single dependency change invalidates all of the file paths going up the dependency chain.

If, then again, your information are primarily based on import maps and identifiers, you may replace a file path in a single location, and no different file must be touched.

<script sort="importmap">
{
  "imports": {
    "foremost": "./foremost.982jda.js",
    "module": "./module.a93mwld.js",
    "dep": "./dep.has83ks.js"
  }
}
</script>

There is no change when a dependency was up to date! 👏 👇


import { module } from 'module';


import { dep } from 'dep';

That is fairly candy and I am unable to wait to see it in motion!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments