【问题标题】:Grunt-replace : parametric json fileGrunt-replace:参数化 json 文件
【发布时间】:2014-11-10 20:39:45
【问题描述】:

早安,

我在我的 gruntfile 中使用 grunt-replace (https://github.com/outaTiME/grunt-replace) 通过从 json 文件加载 json 对象来替换 html 文件中的某些字符串。

我想为这种方法增加一些灵活性,我定制了另一个名为“setopts”的任务,它只是向我使用的 grunt.option 添加一些属性,我通过以下方式在“替换”任务中使用:

replace: {
    common: {
      options: {
        patterns: [
          {
            json: '<%=grunt.option("locales")%>'
          }
        ]
      },
      files: [
        {expand: true, flatten: true, src: ['public/sites/<%=grunt.option("domain")%>/index.html'], dest: 'public/sites/<%=grunt.option("domain")%>/'},
      ]
    }
}    

这是我的“setopts”任务:

grunt.registerTask('setopts', function (domain) {

  locales = grunt.file.readJSON('src/locales/domain/myfile.json');
  grunt.option('locales', locales);

  grunt.option('domain', domain);

}  

我运行以下任务:

grunt.registerTask('maintask',    [ 'setopts:mydomain', 'replace:common']);

经过一些尝试,我发现“替换”任务中的“文件”属性工作正常,但“模式”属性出现错误:

处理源...错误 警告:处理“public/sites/xxxxx/index.html”文件时出错。使用 --force 继续。

这是怎么回事?

感谢您的任何评论!

【问题讨论】:

    标签: javascript json gruntjs


    【解决方案1】:

    我知道我迟到了 1.5 年,但也许其他人可能需要这个问题的答案。

    我让它工作的方式是不使用grunt.option。相反,我使用了grunt.config.set

    replace: {
        common: {
          options: {
            patterns: [
              {
                json: '<%= locales %>'
              }
            ]
          },
          files: [
            {expand: true, flatten: true, src: ['public/sites/<%= domain %>/index.html'], dest: 'public/sites/<%= domain %>/'},
          ]
        }
    }   
    

    注意locales 变量用作json 属性值的方式。

    这是setopts 任务:

    grunt.registerTask('setopts', function (domain) {
    
      locales = grunt.file.readJSON('src/locales/domain/myfile.json');
      grunt.config.set('locales', locales);
    
      grunt.config.set('domain', domain);
    
    }  
    

    希望它可以帮助某人:)

    这个问题帮我找到了答案Programmatically pass arguments to grunt task?

    【讨论】:

      猜你喜欢
      • 2017-12-31
      • 1970-01-01
      • 2022-01-21
      • 2015-12-22
      • 2015-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      相关资源
      最近更新 更多