Grunt – 如何更新js文件中使用gruntcaching胸围的HTML文件引用?
在我的js文件中,我引用了HTML文件,比如window.location。 我想gruntcaching破坏更新该引用并添加散列数据,所以加载的页面是正确的,使用正确的版本文件。 例如:
window.location ='myweb.html'; > window.location ='myweb.html?575a2aa1158af941?575a2aa9658af941';
我无法find任何configuration的caching半身像允许我在js文件中写入。 在我的Gruntfile.js中,我添加了必须写入的资产和scr文件,但没有成功。
我无法find任何configuration的caching半身像允许我在js文件中写入
…我也无法做到这一点。
最后,我select了一个自定义的解决scheme来实现这一点。 这涉及到:
- 使用名为randomstring的节点包生成我自己的随机string。
$ npm install randomstring --save-dev
- 将随机string设置为我的
cacheBust
任务中options.hash
的值。 - 使用grunt-text-replace在
.js
文件中search“.html”,并用新生成的随机string和“.html”replacefind的任何实例。 例如'.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']); };
笔记:
- 上述要点中的任何path引用都需要根据您的项目目录进行更新。
- 在上面的要点中也使用了load-grunt-tasks :
$ npm install load-grunt-tasks --save-dev
-
replace:js
任务中使用的正则expression式将在.js
文件中search字符“.html'
所有实例。 - 你可以指定no。 随机生成的string中通过传递值作为参数出现的字符。 例如
randomstring.generate(7)
我曾经在一个使用Gruntcaching半身像的项目中,在JS文件中使用了文件名。 configuration看起来像这样
cacheBust : { revProd: { options: { assets: ['**/*.js', '!assets/js/config.constant.js','**/*.css','!assets/css/themes/*.css'], baseDir: 'standardversion', deleteOriginals: true, jsonOutput: true, // Output the original => new URLs to a JSON file jsonOutputFilename: 'grunt-cache-bust.json' }, src: ['standardversion/index.html', 'standardversion/assets/js/config.contants.js'] }
我的config.contants.js
文件具有类似的path
'propertiesCtrl': 'assets/views/properties/controllers/properties.controller.js', 'propertyDetailsCtrl': 'assets/views/properties/controllers/propertyDetails.controller.js', 'propertyAddCtrl': 'assets/views/properties/controllers/addProperty.controller.js',
您可以通过将**/*.html
添加到assets
选项来突破**/*.html