javascript - Grunt - 如何使用 grunt 缓存破坏更新 js 文件中的 html 文件引用?

标签 javascript node.js caching gruntjs

在我的 js 文件中,我引用了 HTML 文件,例如 window.location。我希望 grunt cache bust 更新该引用并添加哈希数据,因此加载的页面是正确的页面,即使用正确版本化文件的页面。例如:

window.location = 'myweb.html'; > window.location = 'myweb.html?575a2aa1158af941?575a2aa9658af941';

我找不到任何允许我在 js 文件中写入的缓存中断配置。在我的 Gruntfile.js 中,我添加了 Assets 和必须写入的 scr 文件,但没有成功。

最佳答案

I can't find any configuration of the cache bust that allows me to write within the js file

...我也做不到。

最后,我选择了一个自定义的 grunt 解决方案来实现这一点。这需要:

  1. 利用名为 randomstring 的 Node 包生成我自己的随机字符串。

$ npm install randomstring --save-dev

  1. 在我的 cacheBust 任务中将生成的随机字符串设置为 options.hash 的值。
  2. 利用grunt-text-replace.js 文件中搜索 '.html' 并将找到的任何实例替换为新生成的随机字符串加上 ' .html'。例如。 '.a5G5p7QdOE6DF1St4k.html'。

$ npm install grunt-text-replace --save-dev


Gruntfile.js

module.exports = function(grunt) {

    var randomstring = require("randomstring");

    grunt.initConfig({

        randomString: randomstring.generate(),

        cacheBust: {
            myTarget: {
                options: {
                    // <-- Your options here 
                    hash: '<%= randomString %>' //<-- This template references the random generated string.
                },
                src: [/* Your settings here */]
            }
        },

        replace: {
            js: {
                src: './src/**/*.js',
                dest: './dist/', //<-- creates a copy
                replacements: [{
                    from: /\.html'/, // matches all instances of .html'
                    to: '.<%= randomString %>.html\'' //<-- Note the dot separator at the start.
                }]
            }
        }

    });

    require('load-grunt-tasks')(grunt);

    grunt.registerTask('myCacheBust', ['cacheBust:myTarget', 'replace:js']);
    grunt.registerTask('default', ['myCacheBust']);

};

注意事项:

  1. 上述要点中的任何路径引用都需要根据您的项目目录进行更新。
  2. load-grunt-tasks也用在上面的要点中:

$ npm install load-grunt-tasks --save-dev

  1. replace:js 任务中使用的正则表达式在 .js 文件中搜索字符 .html' 的所有实例。
  2. 您可以指定编号。通过将值作为参数传递出现在随机生成的字符串中的字符数。例如。 randomstring.generate(7)

关于javascript - Grunt - 如何使用 grunt 缓存破坏更新 js 文件中的 html 文件引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41758879/

相关文章:

javascript - 强制浏览器仅缓存图像(不缓存脚本和链接)

multithreading - 您是否期望 future 的 CPU 代不会缓存一致?

javascript - Angular ng-repeat 用于选择,使用 $rootScope 变量将一个选项设置为选中

javascript - JQuery 事件监听器未触发 - Phonegp/Google map

javascript - grunt 任务完成后如何打印文本?

javascript - 如何使用@default 和 degenerated() 在 prisma 中声明数据库默认值?

javascript - 在 X-Editable jQuery 库生成的 Textarea 字段上运行 Textarea Resizer jQuery 插件

javascript - 调用API后,我无法检测innerHTML中的api数据

node.js - Mongoose - 根据分数或权重在三个字段中搜索文本

python - Django 从 shell 检查本地内存缓存