2014-02-05 38 views
1

我正在開發一個Angular Demo應用程序,我想自動化很多事情。GruntJS可配置首次運行

這是一種樣板,儘管是一個更復雜的樣板,我想製作一個配置文件,在其中我們將API密鑰和其他東西,我希望該文件由Grunt與用戶交互當項目第一次啓動時。

喜歡的東西:

grunt build - 它應該直接問用戶在控制檯中的API密鑰,會在我定義整個應用程序的一些全局常量配置文件插入。

Grunt有沒有這樣的功能的例子?

回答

1

您可以通過使用處理追問:

https://github.com/dylang/grunt-prompt

這是一個不錯的小插件,做一個工作,並把它做好。它把任何價值,你在命令行已進入變量:(例子)

prompt: { 
    target: { 
     options: { 
     questions: [ 
      { 
      config: 'key', // arbitrary name or config for any other grunt task 
      type: 'input', // list, checkbox, confirm, input, password 
      message: 'What is your API key?', 
      default: '', // default value if nothing is entered 
      when: function(answers) { return !grunt.file.exists('config.yml'); } // only ask this question when this function returns true 
      } 
     ] 
     } 
    } 
    } 

然後你可以使用Grunt.file功能這些值寫入文件:

http://gruntjs.com/api/grunt.file#grunt.file.write

爲了管理它,你需要創建一個自定義任務:(例子)

grunt.registerTask("my_config_task", function (arg) { 
    var key = arg || grunt.config('key'); 

    grunt.file.write("config.yml", key); 
}); 

grunt.registerTask('build', ['prompt', 'my_config_task']); 

寫作可能需要細化爲你W¯¯病了,我想,需要更換的價值觀和組織作爲yml文件或json對象,等...

找到可能的解決方案之一,而看的grunt-bump來源。他們在做什麼是解析配置文件作爲一個JSON對象:

https://github.com/darsain/grunt-bumpup/blob/master/tasks/bumpup.js#L128

更換他們需要的任何值(如JSON)並覆蓋目標文件字符串化:

https://github.com/darsain/grunt-bumpup/blob/master/tasks/bumpup.js#153

似乎運作良好。

+0

真棒!你先生是救生員......謝謝! –

+0

唯一的這是我需要它只發生一次,我需要看看保存變量的位置,並且不要求用戶添加一次。 –

+0

這就是「when」屬性的用途:when:function(answers){return!grunt.file.exists('config.yml'); } –