在我的 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 解决方案来实现这一点。这需要:
- 利用名为 randomstring 的 Node 包生成我自己的随机字符串。
$ npm install randomstring --save-dev
- 在我的
cacheBust
任务中将生成的随机字符串设置为options.hash
的值。 - 利用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']);
};
注意事项:
- 上述要点中的任何路径引用都需要根据您的项目目录进行更新。
- load-grunt-tasks也用在上面的要点中:
$ npm install load-grunt-tasks --save-dev
replace:js
任务中使用的正则表达式在.js
文件中搜索字符.html'
的所有实例。- 您可以指定编号。通过将值作为参数传递出现在随机生成的字符串中的字符数。例如。
randomstring.generate(7)
关于javascript - Grunt - 如何使用 grunt 缓存破坏更新 js 文件中的 html 文件引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41758879/