【问题标题】:Writing the same config for different targets in Grunt在 Grunt 中为不同的目标编写相同的配置
【发布时间】:2014-01-03 20:30:54
【问题描述】:

我的 Gruntfile 上有一个包含不同目标的任务,所有目标都包含完全相同的字段,只是更改了名称。是否可以以编程方式创建这些目标,只传递目标列表?

我的目标是创建一个已安装子模块的列表,并为每个子模块创建一个目标。具体来说,这个任务不是我的,我正在尝试为咖啡任务创建目标以编译一些文件,但稍后我还需要对把手模板做同样的事情。

我尝试过创建一个通用目标并像这样传递子模块名称:

grunt.initConfig(
    task: {
        target: {
            expand: true,
            flatten: true,
            cwd: "<%= AppModulesPaths[grunt.task.current.args[0]] %>" #"<%= frontend_src %>",
            src: ["<%= AppModulesSources[grunt.task.current.args[0]]%>"],
            dest: "<%= frontend_tmp %>",
            rename: function(dest, src){
                return dest + "<%= grunt.task.current.args[0] %>.js"
            }
       }
    }
})

然后使用 task:target:targetname 注册一个任务数组,但它抱怨 args 未定义。

有什么好的方法吗?

【问题讨论】:

    标签: coffeescript handlebars.js gruntjs


    【解决方案1】:

    当然,它只是普通的 JavaScript。

    function config (targets) {
      var result = {};
    
      targets.forEach(function (target) {
        result[target] = {
          // target configuration here, 
          // optionally tailored to the target's name
        };
      });
    
      return result;
    }
    

    那就用吧

    grunt.initConfig({
      task: config(['target', 'target2', 'target3', 'targetN'])
    });
    

    See fiddle

    【讨论】:

    • 谢谢!但它仍然无法正常工作。从 initConfig 调用 config 时,它说“未定义不是函数”。我尝试在调用 initConfig 之前和之后定义函数(但在外部),没有运气
    • 查看示例小提琴。 jsfiddle.net/9RJun 你可能已经有一个配置变量,我将它重命名为 multi 这样你就不会出现名称冲突
    • 在我的代码中,我将函数命名为 coffeeConfig,但它不起作用。我找到了一种解决方法,创建一个具有所有属性的 Javascript 对象,并在设置完所有内容(包括函数调用)后,使用该对象调用 initConfig。我可以更改您的代码以将其作为答案吗?
    猜你喜欢
    • 1970-01-01
    • 2012-03-14
    • 2016-01-13
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多