2014-02-05 37 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'); } –