Grunt - How to update html files references within js files using grunt cache bust?

后端 未结 3 571
北荒
北荒 2021-01-14 18:19

In my js files I have references to HTML files, like window.location. I would like grunt cache bust to update that reference and add the hash data, so the loaded page is the

3条回答
  •  攒了一身酷
    2021-01-14 18:53

    I've had a similar situation, and I solved by adapting the code above from RobC.

    To avoid problems with cache when deploying, I added a hash after the html reference. By doing so, you force the browser to load the files after deployment, but after that, the files can be cached without problems.

    Here's my code.

    module.exports = function(grunt) {
    
        var randomstring = require("randomstring");
    
        grunt.initConfig({
    
            randomString: randomstring.generate(),
    
            replace: {
                js: {
                    src: './src/**/*.js',
                    dest: './dist/', //<-- creates a copy
                    replacements: [{
                        from: '.js', // use string or regex to find the files you want
                        to: function (matchedWord) {
                            return matchedWord + '?<%= randomString %>';
                        }
                    }]
                }
            }
    
        });
    
        require('load-grunt-tasks')(grunt);
    
        grunt.registerTask('default', ['replace:js']);
    
    };
    

提交回复
热议问题