使用grunt对多个js文件进行Cachebusting

时间:2014-07-10 17:54:03

标签: backbone.js requirejs gruntjs

对于grunt / cachebusting,有几个关于SO的问题,但我找不到足够接近我正在寻找的东西。因此,一个新问题..

这是我正在寻找的。我的Backbone / Marionette应用程序的JS文件被组织到模块级文件夹中。

| - app

|- modules
   |- module1
     |- scripts
        |- models
        |- views
        |- templates
   |- module2
     |- scripts
        |- models
        |- views
        |- templates
|- index.html
|- scripts
    |- app.js
|- styles

我需要的是一种将所有module1连接/缩小/ uglify为其自己的单个文件(比如module1.min.js)的方法。然后应该对该文件进行版本控制,并相应地更新其他JS文件(在其他模块中)中对module1的引用。这样,只有在从客户端调用相应的功能时,我才可以将模块下载到客户端,同时仍然可以获得缓存和缓存清除的好处。如果我将整个应用程序的所有js文件连接到一个文件中,这有助于避免代价高昂的下载。

有没有解决方案?

我确实喜欢开发者JBCP在这个帖子中的答案 - Prevent RequireJS from Caching Required Scripts

然而,它涉及调整requirejs库本身,我的客户不太倾向于这样做(出于显而易见的原因)。

我使用grunt进行构建,因此,我查看了grunt任务 - concat,usemin,rev。我在应用程序中使用requireJS。但我找不到更新来自其他模块的js文件中module1的引用的解决方案,我被卡住了。寻找此问题的解决方案或构建模块级min.js文件以及cachebusting的替代方法。

非常感谢任何帮助。

谢谢, DJ

1 个答案:

答案 0 :(得分:2)

要连接,请使用" grunt-contrib-concat"。

要缩小和uglify JavaScript文件,请使用" grunt-contrib-uglify"。

缓存半身像:

1)使用" grunt-cache-busting" - 它使用文件的md5哈希重命名html中的文件和引用。

2)如果要将自定义字符串附加到文件名

你可以使用" grunt-text-replace"或者" grunt-cache-breaker"重命名html文件中的引用。

你可以使用" grunt-contrib-copy"重命名文件名。

例如: -

module.exports = function (grunt) {
    var timeStamp;

    // Project configuration.
    grunt.initConfig({
copy: {            
            rename: {
                files: [
                    {
                        expand: true,
                        dot: true,
                        cwd: 'js/',
                        dest: 'dist/js/',
                        src: [
                            '*.*'
                        ],
                        rename: function (dest, src) {
                            return dest + src.replace('.js','.' + timeStamp + '.js');
                        }
                    }
                ]
            }
},
replace: {

            bust: {
                src: ['dist/*.html'],
                overwrite: true,                 // overwrite matched source files
                replacements: [
                    {
                        from: '.js',

                        to: function () {
                            timeStamp = new Date().getTime() ;
                            return '.' + timeStamp + '.js';
                        }
                    }
                ]
            }
        }
});
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-text-replace');

要删除原始文件 - 请使用" grunt-contrib-clean"。你可能想要使用另一个" copy"这个任务。

供参考:我的默认任务。 grunt.registerTask('默认',[' clean',' copy:dist',' replace',' copy:rename& #39;,' clean:old',' copy:after',' clean:after']);

相关问题