There are several plugins that can help you with that.
Lets take includereplace for example.
npm install grunt-include-replace --save-dev
You would define the variables you'd like to replace inside your Gruntfile.
Then link to the file you'd like to run the task on.
If you want to add the value through the CLI, you can use the grunt.option
API as you've suggested.
Gruntfile.js
module.exports = function(grunt) {
var ip = grunt.option('ip') || '127.0.0.1';
grunt.initConfig({
includereplace: {
dev: {
options: {
globals: {
ip: ip
},
},
src: 'file.js',
dest: 'dest/'
},
prod: {
options: {
globals: {
ip: ip
},
},
src: 'file.js',
dest: 'dest/'
}
}
});
grunt.loadNpmTasks('grunt-include-replace');
grunt.registerTask('dev', ['includereplace:dev']);
grunt.registerTask('prod', ['includereplace:prod']);
};
file.js
var ip = '@@ip';
I separated the dev and prod configurations so you can add different variables to each environment.
Running grunt prod --ip=XXX.XXX.XXX.XXX
would produce a new file in the dest
folder with the new value.
If you don't like the @@
placeholder convention you can easily change it through the Custom Options API.