Use grunt.config.merge

Most code samples that you’ll find, both on the Grunt web site, and on the readme.md for Grunt plug-ins, will tell you to set the configuration using the grunt.initConfig method:

grunt.initConfig({
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
src: 'src/<%= pkg.name %>.js',
dest: 'build/<%= pkg.name %>.min.js'
}
}
});

The problem with that method is that as you add new tasks to your grunt file, your configuration object will grow, mixing sections from each task. This makes it harder to manage your tasks. Refactoring your file into separate files for each task, for example, will be no fun.

Fortunately, there is another method that doesn’t force you to have one big config object. First, initialize the config without any parameter. This can be done as the first line of your grunt function:

grunt.initConfig();

Then, for each task, use grunt.config.merge:

grunt.config.merge({
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
build: {
src: 'src/<%= pkg.name %>.js',
dest: 'build/<%= pkg.name %>.min.js'
}
}
});

This way, you can keep tidy little blocks of code doing the grunt.loadNpmTasks, the configuration, and the grunt.registerTask in a single place for each task, which is much nicer to read, and to manage.

No Comments