如果添加了新文件,如何使用watch运行gulp任务

时间:2015-01-21 15:51:06

标签: javascript node.js gulp

  

这个问题是关于gulp 3.8.10,使用gulp.watch而不是&gulp-watch'

我有一项任务,将所有html / css / js文件注入我的index.html

gulp.task('index', function () {
  var sources = gulp.src(['./src/**/*.js', './src/**/*.css'], {read: false});
  return gulp.src('./src/index.html')
    .pipe(inject(sources, {ignorePath: 'src', addRootSlash: false }))
    .pipe(gulp.dest('./src'));
});

此任务由以下方式自动触发:

gulp.watch('src/**/*', ['index']);

由于所有这些任务都是,所以将外部文件导入我的index.html,如下所示:

<!-- inject:js -->
<script src="app/app.js"></script>
<script src="module/module.js"></script>
<!-- endinject -->

我想让观察者在添加新文件时运行此任务,重新运行和修改我的index.html是没有意义的文件,当我只是更改已经注入的文件时。

有没有办法用gulp做到这一点?

编辑 接受答案后这里是我的给定示例的实际代码:

gulp.watch('src/**/*', function(event) {
  if (event.type === 'added' ) {
    gulp.start('index');
  }
});

2 个答案:

答案 0 :(得分:8)

在任务或回调中,您将拥有event参数,该参数具有type属性,该参数将告诉您文件是否已添加,删除或更改。最好的选择可能是以你的任务为条件来利用它。

function watcher(event){
   if(event.type === 'added'){ /* do work */ }
}

答案 1 :(得分:0)

对于从Google这里获得的任何人来说,这只是Gulp 4的语法更改。您应该执行以下操作:

gulp.watch('src/**/*', {events: ['add']}, gulp.series('index'));

参考:https://gulpjs.com/docs/en/api/watch#options

相关问题