【问题标题】:In Gulp(4) : Why do you not need an onChange event handler for invoking a stream, but only for reload?在 Gulp(4) 中:为什么不需要 onChange 事件处理程序来调用流,而只需要重新加载?
【发布时间】:2019-05-05 17:18:32
【问题描述】:

我的 gulpfile 4 工作正常。但我只是有点好奇为什么在调用一个调用 browserSync.stream() 的方法时不需要 on('change'....)

下面是我的 Gulp4 gulpfile,它工作正常

但我很好奇为什么在下面的 watch 方法中,我的 sass watch 不需要 onchange 处理程序。

如果我从我的脚本和 html 文件的监视中删除更改处理程序并尝试直接调用 reload,那么这两个将不再起作用。

然而,sass watch 不需要。唔。为什么。

这里是代码

const gulp = require("gulp");
const sass = require("gulp-sass");
const postcss = require("gulp-postcss");
const autoprefixer = require("autoprefixer");
const sourcemaps = require("gulp-sourcemaps");
const browserSync = require("browser-sync").create();

const paths = {
  styles: {
    src: "src/scss/*.scss",
    dest: "src/css"
  },

  scripts: {
    src: "src/js/*.js"
  },

  watched: {
    src: "src/*.html"
  }
};

function style() {
  return gulp
    .src(paths.styles.src)
    //Sourcemaps first so we get mapping once the compilation is done
    .pipe(sourcemaps.init())
    .pipe(sass())
    .on("error", sass.logError)
    //Sass one now run auto prefix
    .pipe(postcss([autoprefixer]))
    //Write the sourcemap
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(paths.styles.dest))
    .pipe(browserSync.stream());
}

//Parallell to this, we need a watch task for the Scss
function watch() {
  browserSync.init({
    server: {
      baseDir: "./src"
    }
  });

  //Watch JavaScript files; just calling reload directly at the moment as we're not babeling
  gulp.watch(paths.scripts.src).on('change', reload);
  //Watch Sass files
  gulp.watch(paths.styles.src, style)
  //Lets make the html our trigger for reload as set in paths object above
  gulp.watch(paths.watched.src).on('change', reload);
}

function reload() {
  browserSync.reload();
}

//Expose to npm
exports.watch = watch;
exports.style = style;

// Default task invoked by typing 'gulp' in npm
gulp.task('default', gulp.parallel(style, watch))

提前谢谢你,我欠你一杯马德拉酒。 托马斯

【问题讨论】:

    标签: gulp browser-sync


    【解决方案1】:

    你可以直接调用reload,但是gulp需要一种知道任务何时完成的方法。添加回调应该可以解决问题:

    function reload(cb) {
      browserSync.reload();
      cb();
    }
    

    【讨论】:

    • 是的;我想我在问这个问题时一定是过度疲劳了。我想我应该用一杯清爽的薄荷茶代替我的晚间咖啡。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    相关资源
    最近更新 更多