javascript - 使用 gulp-watch 运行现有任务

标签 javascript gulp gulp-watch

我已经在 gulpfile.js 中定义了一些任务,并且我想使用 gulp-watch 插件(在新文件上运行任务)。我的问题是,因为我找不到任何东西,我可以在运行监视(来自插件)功能的同时运行现有任务吗?

var gulp = require('gulp'),
    watch = require('gulp-watch'),
    ...;

gulp.task('lint', function () {
  return gulp.src(path.scripts)
      .pipe(jshint())
      .pipe(jshint.reporter(stylish));
});

gulp.task('watch', function () {
  watch({ glob: 'app/**/*.js' }); // Run 'lint' task for those files
});

因为我不想在我的每个任务中都包含 watch() 任务。我只想有 1 个任务 - watch ,它将结合所有“ watch ”。

----- 编辑 ---- (因为我可能没有完全明白我的意思):

我需要从 gulp('watch') 任务内部运行任务。例如:

就像我用 gulp.watch 所做的那样:

gulp.task('watch', function () {
  gulp.watch('files', ['task1', 'task2']);
});

我需要做同样的事情,但是使用 gulp-watch 插件,类似(我知道它不起作用):

var watch = require('gulp-watch');

gulp.task('watch', function () {
  watch({ glob: 'files' }, ['task1', 'task2']);
});

最佳答案

我还遇到了想要使用 gulp-watch (而不是 gulp.watch),需要使用回调形式,并且无法找到合适的方式来在回调中运行任务的问题。

我的用例是我想观看所有手写笔文件,但只处理包括所有其他文件的主手写笔文件。较新版本的 gulp-watch 可能会解决这个问题,但我在 4.3.x 上遇到问题,所以我只能使用 4.2.5。

  • gulp.run 已被弃用,所以我不想使用它。
  • gulp.start 效果很好,但 gulp 作者也建议不要使用,相反。
  • 运行序列插件运行良好,可让您定义运行 命令,但它是一个自称的黑客: https://www.npmjs.com/package/run-sequence
  • Contra 建议编写普通的旧函数并调用 那些。这对我来说是一个新想法,但我认为下面的例子体现了这个想法。 https://github.com/gulpjs/gulp/issues/505

选择吧。

var gulp = require('gulp'),
    watch = require('gulp-watch'), // not gulp.watch
    runSequence = require('run-sequence');

// plain old js function
var runStylus = function() {
    return gulp.src('index.styl')
        .pipe(...) // process single file
}

gulp.task('stylus', runStylus);

gulp.task('watch', function() {
    // watch many files
    watch('*.styl', function() {
        runSequence('stylus');
        OR 
        gulp.start('stylus');
        OR
        runStylus();
    });
});

所有这些都在没有警告的情况下为我工作,但我仍然不确定是否从 4.2.x 版本的 gulp-watch 获取“完成”回调。

关于javascript - 使用 gulp-watch 运行现有任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27952209/

相关文章:

javascript - className() css 样式未显示

javascript - Coffeescript + Browserify + Gulp + Uglify

javascript - Gulp 脚本 [Gulp Watch] - 找不到模块 'browser-sync'

Gulp:如何将参数从 watch 传递给任务

javascript - Webkit 和 Moz Transform,取决于浏览器

javascript - 在javascript中对混合服装尺寸的数组进行排序

javascript - 字符串比较与哈希

npm - gulp 安装全局与本地作为开发依赖

ruby - 使用 gulp 运行 compass 任务会导致 LoadError