NodeJS environment variables in Grunt

bevacqua picture bevacqua · Mar 21, 2013 · Viewed 32.4k times · Source

I'm shifting my project from simply node server.js into using Grunt.

I used to run my application directly from webstorm, and environment variables would be set up for me.

How can I achieve the same in Grunt?

I need to either run grunt from webstorm (windows), or set up env vars when running grunt (explicitly)

This isn't an issue when deploying because heroku already takes care of setting my env vars.

Answer

hereandnow78 picture hereandnow78 · Mar 27, 2013

use the grunt-env plugin: https://npmjs.org/package/grunt-env

and set your config:

grunt.initConfig({
  env : {
    options : {
      //Shared Options Hash
    },
    dev : {
      NODE_ENV : 'development',
      DEST     : 'temp'
    }
  },
  'another-task': {}
});

in your gruntfile you will probably define some default-task:

grunt.registerTask('default', ['env', 'another-task']);

so if you run 'grunt default' at first your env-vars are set, and then 'another-task' is run

if you want to specify the current environment via command-line option you could use grunt.option:

grunt.initConfig({
  env : {
    options : {
      //Shared Options Hash
    },
    dev : {
      NODE_ENV : grunt.option('environment') || 'development',
      DEST     : 'temp'
    }
  },

in this example if you call your grunt task with --environment=production production will be set, otherwise development will be set