Using grunt tasks from gulp

How to reuse grunt tasks from gulp

I have written so far 11 grunt plugins and some of them are pretty useful, like grunt-nice-package that verifies Nodejs package.json. Today a few of my projects use gulp, and I would like to reuse the same logic to verify the package.json file when running gulp. Here is how to run a grunt task from gulp.

  • You will need to install global grunt task runner npm install -g grunt-cli
  • Install gulp-grunt in your project npm install --save-dev gulp-grunt
  • Write a simple gruntfile.js (the name must be gruntfile.js currently). Here is mine
gruntfile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
module.exports = function (grunt) {
grunt.initConfig({
nicePackage: {
all: {
options: {
blankLine: true
}
}
}
});
grunt.loadNpmTasks('grunt-nice-package');
grunt.registerTask('nice-package', ['nicePackage']);
grunt.registerTask('default', function () {
var msg = 'DO NOT USE DIRECTLY\n' +
'to build this project use "gulp"\n' +
'these are just grunt tasks to be used from gulp.';
console.error(msg);
process.exit(-1);
});
};
  • Load grunt tasks from the gulp file
gulpfile.js
1
2
3
4
var isVerbose = process.argv.some(function (arg) {
return arg === '-v' || arg === '--verbose';
});
require('gulp-grunt')(gulp, { verbose: isVerbose });

The gulp-grunt module automatically prefixes all grunt tasks with grunt- prefix. Thus the registered nice-package task will be available from gulp under the name grunt-nice-package.

  • Run the desired grunt tasks gulp grunt-nice-package
  • Add the grunt task to the default task if necessary gulp.task('default', ['grunt-nice-package', ...]);

That is it!

Note The gulp task does not wait for the asynchronous grunt task to finish, thus it will report that the gulp task has finished, while the grunt task actually is still running.