我正在尝试使用 grunt Replace 来更改文件名并向文件添加随机数以防止缓存图像、css 和 js 文件。
所以我正在运行以下代码
module.exports = function replace(grunt) {
var randomVersion = ((new Date()).valueOf().toString()) + (Math.floor((Math.random() * 1000000) + 1).toString());
var replace = {
options: {
variables: {
'randomVersion': randomVersion
},
overwrite: true
},
files: [{
src: './target/dist/index.html',
dest: './target/dist/index.' + randomVersion + '.html'
}]
};
console.log(randomVersion);
grunt.config.set('replace', replace);
};
但我得到的只是“目的地未定义
有人能解释一下吗?
谢谢
最佳答案
我不完全确定你的代码想要实现什么,但我会根据我的理解继续回答。
首先,您是否尝试使用 grunt-replace图书馆?如果是这样,我认为这是不正确的。该库用于替换源文件内容中的值,而不是文件路径本身。
在我看来,您想要做的是将源index.html 文件复制到其中包含唯一标识符的文件路径。您可能尝试将其包装在自定义任务中,但这样做不是必要的。
以下是我如何完成此任务的示例 Gruntfile.js。请注意,此解决方案需要安装 grunt-contrib-clean和 grunt-contrib-copy图书馆。
module.exports = function (grunt) {
grunt.initConfig({
clean: {
dist: ['./target/dist/index.*.html']
},
copy: {
dist: {
src: './target/src/index.html',
dest: './target/dist/index.<%= Date.now() %>.html'
}
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.registerTask('default', ['clean', 'copy']);
};
此解决方案有一些值得指出的地方:
- index.html 文件不在/dist 文件夹中,因为它不是 旨在用于分发,但更确切地说,是一个来源。
- 在创建新版本的index.*.html 之前,我们将删除所有 /dist 文件夹中的现有版本,这样我们就没有 各个版本的积累。
- 我们将使用一个版本号,而不是使用“随机”号 时间戳。这很有帮助,因为每个版本都会有更大的 数量比之前的数量多。
关于javascript - grunt 替换时出现目标未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37580523/