Gulp 网络服务器,过滤器是什么?

Gulp webserver, What is the filter?

我正在学习教程系列,并且我熟悉 Gulp 的原理,但是

I can't seem to find what the Filter function does in the following example

此处也显示了示例,但不提供进一步说明 https://github.com/hiddentao/gulp-server-livereload#how-can-i-pass-a-custom-filter-to-livereload

这是代码。

gulp.task('serve', function(done) {
  gulp.src('')
    .pipe(server({
      livereload: {
        enable: true,
        filter: function(filePath, cb) {
          if(/main.js/.test(filePath)) {
            cb(true)
          } else if(/style.css/.test(filePath)){
            cb(true)
          }
        }
      },
      open: true
    }));
});

简答:

过滤器使您能够排除项目目录中我更改的文件(例如git 文件),但您的服务器不会自动重新加载。您可以在此函数中定义任意逻辑。

更长的答案:

过滤器定义了一个函数,该函数获取已更改文件的 filePath 和触发重新加载的预定义回调函数 cb

function (shouldReload) {
  if (shouldReload) {
    gutil.log('Livereload: file changed: ' + filename);

    config.livereload.io.sockets.emit('reload');
    // Treat changes to sourcemaps as changes to the original files.
    filename = filename.replace(/\.map$/, '');

    config.livereload.io.sockets.emit('file_changed', {
      path: filename,
      name: path.basename(filename),
      ext: path.extname(filename),
    });
  }
}

这意味着如果您调用 cb(true),您的服务器的实时重新加载就完成了。

当我读到你的例子时,你想只有当文件 main.jsstyle.css 被更改时才重新加载你的服务器 。因此,通过 \. 转义 . 可能匹配任何字符(参见正则表达式):

if(/main\.js/.test(filePath)) {
  cb(true)
} else if(/style\.css/.test(filePath)){
  cb(true)
}

意思是执行这个任务。保存和更改 main.jsstyle.css 将触发服务器的实时重新加载。

我的服务器有时会卡住,无法重新加载。按一次 CTRL+C 有助于让他恢复工作 ;-)