【问题标题】:GruntJS Configurable First Time RunGruntJS 可配置的首次运行
【发布时间】:2014-03-01 20:37:51
【问题描述】:

我正在开发一个 Angular 演示应用程序,我想自动化很多事情。

这是某种样板,尽管它更复杂,我想制作一个配置文件,我们将在其中放置 API 密钥和其他东西,并且我希望 Grunt 使用用户交互填充该文件项目首次启动。

类似:

grunt build - 它应该直接在控制台中向用户询问 API 密钥,该密钥将插入到我为整个应用程序定义一些全局常量的配置文件中。

Grunt 有这样的功能示例吗?

【问题讨论】:

    标签: javascript node.js angularjs gruntjs


    【解决方案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']);
    

    写作可能需要改进,我猜你需要替换值并组织为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

    看起来效果不错。

    【讨论】:

    • 太棒了!您先生是救生员...谢谢!
    • 唯一的就是我需要它只发生一次,我需要查看保存变量的位置,如果用户添加了一次,不要询问它们。
    • 这就是“when”属性的用途:when: function(answers) { return !grunt.file.exists('config.yml'); }
    • 只有在函数返回 true 时才会提出问题
    • 是的,我还没有正确阅读代码,下班后,还是谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多