Arthur Kovacs
Arthur Kovacs

Reputation: 1740

GruntJS Configurable First Time Run

I am working on a Angular Demo Application and I want to automatize a lot of things.

It's some sort of a boilerplate, albeit a more complex one, and I want to make a config file in which we'll put API Keys and other stuff, and I want that file to be populated by Grunt with user interaction when the project is started for the first time.

Something like:

grunt build - it should ask the user directly in the console for the API keys, that will be inserted in the config file where I am defining some global constants for the entire App.

Is there such an example of functionality with Grunt ?

Upvotes: 1

Views: 66

Answers (1)

Aurélien Thieriot
Aurélien Thieriot

Reputation: 5923

You can handle the questioning by using:

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

It is a nice little plugin that do one job and do it well. It put whatever value you have entered in the command line into variables: (example)

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
          }
        ]
      }
    }
  }

Then you can use the Grunt.file functions to write those values into files:

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

To orchestrate it, you will need to create a custom task: (example)

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']);

The writing will likely need refinement as you will, I guess, need to replace values and organise as a yml file or json object, etc...

Found one of the possible solutions while looking at the sources of grunt-bump. What are they doing is parsing the config file as a JSON object:

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

Replacing whatever values they need (as JSON) and overwrite the file with the object stringified:

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

Seems to work well.

Upvotes: 1

Related Questions