Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cache bust imported modules in es6?

ES6 modules allows us to create a single point of entry like so:

// main.js    import foo from 'foo';    foo()
<script src="scripts/main.js" type="module"></script>

foo.js will be stored in the browser cache. This is desirable until I push a new version of foo.js to production.

It is common practice to add a query string param with a unique id to force the browser to fetch a new version of a js file (foo.js?cb=1234)

How can this be achieved using the es6 module pattern?

like image 850
spinners Avatar asked Dec 06 '17 13:12

spinners


People also ask

Can I use ES6 imports?

Importing can be done in various ways:Node js doesn't support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error.

Are JavaScript modules cached?

HTML files are never cached. JavaScript bundles, styles and other assets are cached forever.

Does ES6 Import Export?

With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module.

Can ES6 modules have side effects?

Examples of side effects:A polyfill that enables ES6 features in the browsers that don't support them, like babel polyfill is a side effect. Many jQuery plugins attach themselves to the global jQuery object. Analytics modules that run in the background, monitor user interaction, and send the data to a server.


1 Answers

There is one solution for all of this that doesn't involve query string. let's say your module files are in /modules/. Use relative module resolution ./ or ../ when importing modules and then rewrite your paths in server side to include version number. Use something like /modules/x.x.x/ then rewrite path to /modules/. Now you can just have global version number for modules by including your first module with <script type="module" src="/modules/1.1.2/foo.mjs"></script>

Or if you can't rewrite paths, then just put files into folder /modules/version/ during development and rename version folder to version number and update path in script tag when you publish.

like image 60
Wanton Avatar answered Sep 20 '22 18:09

Wanton