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

后端 未结 4 1782
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-21 06:50

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

4条回答
  •  悲&欢浪女
    2021-01-21 07:22

    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

提交回复
热议问题