【问题标题】:grunt task with custom json config带有自定义 json 配置的 grunt 任务
【发布时间】:2013-01-31 08:27:30
【问题描述】:

我想创建某种任务,我可以从不同的 json 文件中读取自定义配置,并将咖啡源文件中的内容替换为 json 文件的内容,并连接源文件。

我的项目设置:

  • ./src

    • file1.coffee
    • file2.coffee
  • ./配置

    • /文件夹1

      • development.json(包含:{“key”:“value1”}
      • production.json(包含:{“key”:“value2”}
    • /文件夹2

      • development.json(包含:{“key”:“value3”}
      • production.json(包含:{“key”:“value4”}
  • ./dist

    • 包装名称.coffee
    • 包名.js

file1.coffee 包含

myVar = '@@putkeyhere'
version = '@@version'
...

我已经为自己配置并运行了 grunt concat 任务:

concat: {
  dist: {
    src: ['<banner>', './src/*.coffee'],
    dest: './dist/<%= pkg.name %>.coffee'
  }
},

我得到了 grunt-replace 任务(当我在已经连接的文件上运行“grunt replace”时,版本的替换等已经在工作了)

replace: {
  dist: {
    options: {
      variables: {
        'created': '<%= grunt.template.today("dd.mm.yyyy HH:MM:ss") %>',
        'environment': 'dev',
        'version': '<%= pkg.version %>'
      },
      prefix: '@@'
    },
    files: {
      'dist/': ['./dist/<%= pkg.name %>.coffee']
    }
  }
},

最后是咖啡编译任务:

coffee: {
  compile: {
    files: {
      './dist/<%= pkg.name %>.js': ['./dist/*.coffee']        
    }
  }
}

所有任务都为自己工作,但我需要从 config-json 文件中读取内容并将内容替换为串联的咖啡文件,然后将所有文件编译为 js。

我尝试了类似的方法,但感觉不对:

grunt.registerTask('mytask', '', function (env) {

  env = env || 'development';
  if (env !== 'development' && env !== 'production') {
    grunt.log.error("'" + env + "' is not valid environment");
    return false;
  }

  var c = grunt.option('c');
  if(c) {

    // if i run the task "grunt mytask:production -c folder2 it should read
    // ./config/folder2/development.json
    // that works that way, but i dont think this is a good solution
    var config = grunt.file.readJSON('./config/' + c + '/' + env + '.json')


  } else {

     // here i need to iterate for all folders in ./config, and do stuff for all
  }

});

multiTask 是一个选项吗?但是如何从 config.json 文件中动态读取呢?

感谢您的帮助!

【问题讨论】:

    标签: javascript json coffeescript gruntjs


    【解决方案1】:

    我找到了一个插件可以帮助你实现这一点 - https://github.com/outaTiME/grunt-replace

    【讨论】:

      猜你喜欢
      • 2014-06-03
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      • 2013-06-09
      • 2017-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多