Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

require.js - How can I set a version on required modules as part of the URL?

I am using require.js to require JS modules in my application.

I need a way to bust client cache on new JS modules, by way of a different requested URL.

i.e., if the file hello/there.js has already been cached on the client, I can change the file name to force the browser to get the new file.

In other words, for the module hello/there, I'd like require.js to request the url hello/there___v1234___.js (the file name can look different, it's just an example), according to a version string which is accessible on the client.

What is the best way to achieve that?

like image 902
Ovesh Avatar asked Dec 27 '22 13:12

Ovesh


1 Answers

I got really frustrated with the urlArgs solution and finally gave up and implemented my own fix directly into require.js. This fix implements your ideal solution, if you are willing to modify your version of the library.

You can see the patch here:

https://github.com/jbcpollak/requirejs/commit/589ee0cdfe6f719cd761eee631ce68eee09a5a67

Once added, you can do something like this in your require config:

var require = {
    baseUrl: "/scripts/",
    cacheSuffix: ".buildNumber"
}

Use your build system or server environment to replace buildNumber with a revision id or software version.

Using require like this:

require(["myModule"], function() {
    // no-op;
});

Will cause require to request this file:

http://yourserver.com/scripts/myModule.buildNumber.js

The patch will ignore any script that specifies a protocol, and it will not affect any non-JS files.

On our server environment, we use url rewrite rules to strip out the buildNumber, and serve the correct JS file. This way we don't actually have to worry about renaming all our JS files.

This works well for my environment, but I realize some users would prefer a prefix rather than a suffix, it should be easy to modify my commit to suit your needs.

Here are some possible duplicate questions:

RequireJS and proxy caching

Prevent RequireJS from Caching Required Scripts

like image 82
JBCP Avatar answered Apr 06 '23 00:04

JBCP