从 Gulp 运行 Grunt 任务
可以从 Gulp 内部运行 Grunt 任务/Grunt 插件。这在从 Grunt 逐步迁移到 Gulp 或者有特定插件需求时非常有用。使用所描述的方法,不需要 Grunt CLI 和 Gruntfile。
这种方法需要 Grunt >=1.0.0
非常简单的 gulpfile.js
示例:
// npm install gulp grunt grunt-contrib-copy --save-dev
var gulp = require('gulp');
var grunt = require('grunt');
grunt.initConfig({
copy: {
main: {
src: 'src/*',
dest: 'dest/'
}
}
});
grunt.loadNpmTasks('grunt-contrib-copy');
gulp.task('copy', function (done) {
grunt.tasks(
['copy:main'], //您可以在此数组中添加更多的 grunt 任务
{gruntfile: false}, //不要寻找 Gruntfile - 没有这个文件。:-)
function () {done();}
);
});
现在用以下命令启动任务:
gulp copy
使用上述方法,grunt 任务会在 gulp 的任务系统中注册。请记住,grunt 任务通常是阻塞的(与 gulp 不同),因此在 grunt 任务完成之前,没有其他任 务(即使是 gulp 任务)可以运行。
关于替代方案的几句话
有一个 gulpfriendly 的 node 模块 gulp-grunt
可用,它采用了不同的方法。它生成子进程,并在其中执行 grunt 任务。但这种工作方式意味着有一些限制:
- 目前无法通过
gulp-grunt
向 grunt 任务传递选项/CLI 参数等 - 所有 grunt 任务必须在单独的 Gruntfile 中定义
- 您需要安装 Grunt CLI
- 一些 grunt 任务的输出会格式错乱(例如颜色编码)。