【问题标题】:Destination not defined error on grunt replace咕噜替换时未定义目标错误
【发布时间】:2016-10-01 12:31:15
【问题描述】:

我正在尝试使用 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);
};

但我得到的只是“目的地未定义

任何人都可以对此有所了解吗?

谢谢

【问题讨论】:

    标签: javascript replace npm gruntjs


    【解决方案1】:

    我不完全确定你的代码试图达到什么目的,但我会根据我的理解继续回答。

    首先,您是否尝试使用grunt-replace 库?如果是这样,我认为这是不正确的。该库用于替换源文件内容中的值,而不是文件路径本身。

    在我看来,您想要做的是将源 index.html 文件复制到其中包含唯一标识符的文件路径。您可能会尝试将其包装在自定义任务中,但没有必要这样做。

    以下是我将如何完成此任务的示例 Gruntfile.js。请注意,此解决方案需要安装 grunt-contrib-cleangrunt-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']);
    
    };
    

    这个解决方案有几点值得指出:

    • /dist 文件夹中的 index.html 文件不在,因为它不在 旨在分发,但实际上是一个来源。
    • 在创建新版本的 index.*.html 之前,我们将删除任何 /dist 文件夹中的现有版本,因此我们没有 每个版本的积累。
    • 我们的版本不使用“随机”数字,而是使用 时间戳。这很有帮助,因为每个版本都会有更大的 比前面的数字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      • 1970-01-01
      • 1970-01-01
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多