gulp.watch() not running subsequent task

我们两清 提交于 2019-12-13 01:19:32

问题


Running into a bizarre bug when trying to make modular gulp tasks by splitting them into separate files. The following should execute the task css, but does not:

File: watch.js

var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();

gulp.task('watch', function () {
  plugins.watch('assets/styl/**/*.styl', ['css']); // PROBLEM
});

Declaring ['css'] in plugins.watch() should technically run the following task next:

File: css.js

var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();

gulp.task('css', function () {
  return gulp.src('assets/styl/*.styl')
    .pipe(plugins.stylus())
    .pipe(gulp.dest('/assets/css'));
});

File: gulpfile.js

var gulp = require('gulp');
var requireDir = require('require-dir');
requireDir('./gulp/tasks', { recurse: true });

gulp.task('develop', ['css', 'watch']);

Folder structure

- gulp/ - tasks/ - css.js - watch.js - gulpfile.js


Expected behavior

gulp develop should run tasks css and watch (it does). On file changes, watch should detect them (it does) and then run the css task (it's does not).

One solution

Not terribly fond of this solution as gulp.start() is being deprecated in the next release, but this does fix it:

File: watch.js

plugins.watch('assets/styl/**/*.styl', function() {
  gulp.start('css');
});

回答1:


Either use gulp's builtin watch with this syntax:

gulp.task('watch', function () {
  gulp.watch('assets/styl/**/*.styl', ['css']);
});

Or gulp-watch plugin with this syntax:

gulp.task('watch', function () {
  plugins.watch('assets/styl/**/*.styl', function (files, cb) {
    gulp.start('css', cb);
  });
});

There's also probably a typo in your gulp.dest path. Change it to relative:

.pipe(gulp.dest('assets/css'));



回答2:


I am using Gulp 4, where gulp.start() is deprecated

So here's the solution

gulp.task('watch', gulp.series('some-task-name', function () {
    browserSync.init({
        server: {
            baseDir: config.distFolder + ''
        }
    });

    var watcher = gulp.watch([
                    './src/views/*.html', 
                    './src/index.html', 
                    './src/assets/css/*.css', 
                    './src/**/*.js'],
                    gulp.series('some-task-name'));
    watcher.on('change', async function (path, stats) {
        console.log('you changed the code');
        browserSync.notify("Compiling, please wait!");
        browserSync.reload();
    })
}));

Now, whenever there is a change in my code, my "some-task-name" gets executed and then the browser page is reloaded. I don't need to delay my browser-sync at all.



来源:https://stackoverflow.com/questions/26476226/gulp-watch-not-running-subsequent-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!