Pass an environment variable from grunt to a file

Viewed 1502

Depending on the environment, I want to run HTTP requests in a js file to a URL or another.

For example, I have something like this:

What I want is to execute the grunt file and specify the env, so the js file should read the option and make the requests to an URL or another.

For instance:

grunt default --env=prod

How can I say to the js file that the URL is the dev, preprd or prod one?

1 Answers

Node.js API exposes process object, which stores environment variables inside its env property. Every environmental variable set before runtime will be inside process.env.

For example:

$ NODE_ENV=production node -e 'console.log(process.env.NODE_ENV)'

will output:

production

In your particular case, you can use process.env inside your Gruntfile.js and then, when running grunt, you can use it like the example above.

Sample Gruntfile.js with environment variables

Adapted from Grunt.js website

module.exports = function(grunt) {

  grunt.initConfig({
    jshint: {
      files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
      options: {
        globals: {
          jQuery: true
        }
      }
    },
    watch: {
      files: ['<%= jshint.files %>'],
      tasks: process.env.PRODUCTION ? [] : ['jshint']
    }
  });

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.registerTask('default', ['jshint']);
};

Then, if you run

$ grunt watch # PRODUCTION environment variable is not set

it will execute jshint task when watching files. On the other hand, if you set the PRODUCTION variable and run the same command

$ PRODUCTION=true grunt watch

it won't execute any task when watching files.

Related