3

I have an HTML5+JS code that is being built by Grunt. I'm currently setting up both a development and a production environment.

Is there a way to pass parameters from Grunt to the JS code? This way I could pass the IP of the development/production server, depending which one I'm building.

By the way, I noticed that the Grunt option allows defining Grunt parameters (http://gruntjs.com/api/grunt.option), but how can I use them within the JS code?

If there is a better practice for setting up two environments for a JS project please let me know.

Thanks!

David Ben Ari
  • 2,259
  • 3
  • 21
  • 40
  • It would be a good idea to look at this question: http://stackoverflow.com/questions/12401998/have-grunt-generate-index-html-for-different-setups – kartikluke Apr 16 '15 at 21:14

1 Answers1

0

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.

LifeQuery
  • 3,202
  • 1
  • 26
  • 35