Search code examples
javascriptecmascript-6gruntjsbabeljstranspiler

How to pass dynamic config to Gruntfile.js


I have written the grunt task to transpile ES6 to ES5. Following is my Gruntfile.js file

module.exports = function (grunt)
{
    require("load-grunt-tasks")(grunt);

    grunt.initConfig({
        "babel": {
            options: {
                presets: ['es2015']
            },
            dist: {
                files: [{
                  expand: true,
                  cwd: '/Users/pankajmeshram/Documents/IVWorkSpace/enfresh/resources/modules',
                  src: ['**/*.es6'],
                  dest: '/Users/pankajmeshram/Documents/IVWorkSpace/enfresh/resources/modules',
                  ext: '.js'
              }]
            }
        }
    });

    grunt.registerTask("default", ["babel"]);
};

In this file, I want to pass the cwd and dest option dynamically so that I can use this for the different project as well as we have common build for all our projects.

If anyone work on this before, you can suggest some ways or any alternative solution for this task.


Solution

  • module.exports = function(grunt) {
        require("load-grunt-tasks")(grunt);
    
        grunt.initConfig({
            "babel": {
                options: {
                    presets: ['es2015']
                },
                dist: {
                    files: [{
                        expand: true,
                        cwd: "<%= cwd %>",
                        src: ['**/*.es6'],
                        dest: "<%= dest %>",
                        ext: '.js'
                    }]
                }
            }
        });
    
        grunt.registerTask("dynamicConfigs", "Set Dynamic Configs", function (argName, argValue) {
            grunt.config.set(argName, argValue);
        });
    
        grunt.registerTask("default", ["dynamicConfigs:cwd:/Users/vineethgn/Documents/IVWorkSpace/enfresh/resources/modules", "dynamicConfigs:dest:/Users/vineethgn/Documents/IVWorkSpace/enfresh/resources/modules", "babel"]);
    };
    

    You can define those properties as template and then before calling babel task, call the newly created dynamicConfigs task. Inside dynamicConfigs you are basically setting the key-value pair in grunt.config. Make sure to call dynamicConfigs task with the parameters you want to set like in the sample code above.