23

I have some code in a grunt.js file which is working with 0.3 but breaks on 0.4:

{
    dest: '<%= process.env.DEST %>/index.html'
}

In 0.3 process is defined and so I can access variables defined in the environment inside the template when I am e.g. passing file paths to other plugins.

Is there an alternative approach to this which will work in 0.4? Or a way to put a breakpoint in while the template is rendering so that I can see what variables are available?

vitch
  • 3,215
  • 3
  • 25
  • 26

2 Answers2

54

The default data is the config object. You can add the environment variable to the config object or just use it directly.

grunt.initConfig({
    destination: process.env.DEST,
    task: {
        target: {
            dest: '<%= destination %>/index.html'
        }
    },
});

or

grunt.initConfig({
    task: {
        target: {
            dest: process.env.DEST + '/index.html'
        }
    },
});
Sanghyun Lee
  • 21,644
  • 19
  • 100
  • 126
Sindre Sorhus
  • 62,972
  • 39
  • 168
  • 232
  • Thanks for the very clear answer - that's demystified something that had me confused! – vitch Jan 02 '13 at 14:05
  • 3
    Note that the documentation @SindreSorhus mentions has moved to http://gruntjs.com/api/grunt.config. – Ludder Nov 22 '13 at 14:49
0

That's a great straight forward answer by Sindre. Alternatively you can do (use the grunt-env plugin: https://npmjs.org/package/grunt-env )-

grunt.initConfig({
    env : {
        test : {
            DEST : 'testDEST'
        },
        dev : {
            DEST : 'devDEST'
        },
        qa : {
            DEST : 'qaDEST'
        },
        prod : {
            DEST : 'prodDEST'
        }
    }

});


grunt.registerTask('setenvs', 'Set environment variables', function() {
    grunt.config('ENVS', process.env);
});

and then use

{
    dest: '<%= ENVS.DEST %>/index.html'
}

Your task would be -

    grunt.registerTask('default', [
        'env:dev',
        'setenvs'
        'yourTask'
    ]);

Proposed alternative approach just so that you can use <%= ... %> and you don't have to hardcode it in initConfig. Target for env you can take as input from user and pass it to env.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • Is is possible to load environment variables from files with grunt-env, right? how can you access them? I'm currently failing to do that. I would like to access a .env file that I'm already using with webpack. Is it possible? Thx! – DraQ Mar 30 '20 at 20:15