Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript module versioning

In my web application I developed several (vanilla+jQuery) javascript modules. Unfortunately I don't know how to manage their versioning.

The argument of script versioning is very discussed and has different solution as described here for example. Instead in case of modules I didn't found any valid mechanism to version my files.

An example of my code is:

myJsFile.js

import A from './js/A.js';

const a = new A();
a.doStuff();

A.js

export default class A {

    constructor() {}

    doStuff() {
        console.log("I hope to have a version, one day");
    }
}

How can I prevent browsers from using old cached versions of module A?

like image 575
Timmy Avatar asked May 27 '26 01:05

Timmy


1 Answers

You can add a query to the end of the import file:

import A from './js/A.js?version=1.1';

const a = new A();
a.doStuff();

Note: You should then make sure all your imports of the same file across your platform should use the same version number otherwise the module can get imported multiple times. To manage this, you can either do a global find/replace "?version=X" to update all version numbers at once, or create an import map on a global HTML file you include at the head to manage them easier. For example, if you are using PHP, you can add a section to your HTML heads:

<script type="importmap">
    {
        "imports": {
            "moduleA": "./js/A.js?version=<?=VERSION?>",
            "moduleB": "./js/B.js?version=<?=VERSION?>",
            ...
        }
    }
</script>

Then you can import the module as:

import A from 'moduleA';

const a = new A();
a.doStuff();
like image 116
msawired Avatar answered May 28 '26 15:05

msawired



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!