gulp 在终端中复制任务

gulp duplicating tasks in the terminal

我的gulp有问题,我不知道怎么解释,但是你看到就明白了,基本上,我认为我的gulp是重复的任务和执行可能需要一段时间,但如果我完成 gulp 并再次执行它,问题不会在第一次编译时发生,但随着时间的推移它会重复越来越多(第一次加倍, 然后是 4x, 8x 等等)

我的gulp:

    var gulp = require('gulp'),
    //Js
    babel = require('gulp-babel');
    uglify = require('gulp-uglify'),
    filesJs = './js/edit/*.js',
    outputJs = './js',
    //Sass
    sass = require('gulp-sass'),
    filesCss = './css/**/*.+(scss|sass)',
    outputCss = './css';
const {
    watch
} = require('gulp');

//Uglify
gulp.task('uglify', function () {
    gulp.src(filesJs)
        .pipe(babel({presets: ['@babel/preset-env']}))
        .pipe(uglify())
        .pipe(gulp.dest(outputJs));
});

const watcherJS = watch([filesJs]);
watcherJS.on('change', function (path, stats) {
    console.log(`File ${path} was changed`);
    return gulp.watch(filesJs, gulp.series('uglify'));
});

//Sass
gulp.task('sass', function () {
    return gulp.src(filesCss)
        .pipe(sass({
            outputStyle: 'compressed'
        }).on('error', sass.logError))
        .pipe(gulp.dest(outputCss));
});

const watcherCSS = watch([filesCss]);
watcherCSS.on('change', function (path, stats) {
    console.log(`File ${path} was changed`);
    return gulp.watch(filesCss, gulp.series('sass'));
});

//Run/Watch
gulp.task('default', gulp.parallel('uglify', 'sass'));

我的终端保存 .sass 文件一次后

File css\style.sass was changed
[09:43:18] Starting 'sass'...
[09:43:18] Starting 'sass'...
[09:43:18] Starting 'sass'...
[09:43:18] Starting 'sass'...
[09:43:33] Finished 'sass' after 15 s
[09:43:33] Finished 'sass' after 15 s
[09:43:33] Finished 'sass' after 15 s
[09:43:33] Finished 'sass' after 15 s

几乎可以肯定是您使用了 chokidar 手表功能。您的代码甚至 运行 都不适合我。而且您不需要那么复杂。我建议摆脱

const watcherJS = watch([filesJs]);
watcherJS.on('change', function (path, stats) {
    console.log(`File ${path} was changed`);
    return gulp.watch(filesJs, gulp.series('uglify'));  // this is very strange, must be wrong
});

const watcherCSS = watch([filesCss]);
watcherCSS.on('change', function (path, stats) {
    console.log(`File ${path} was changed`);
    return gulp.watch(filesCss, gulp.series('sass'));
});

并替换为:

gulp.task('watchFiles', function () {
    gulp.watch(filesCss, gulp.series('sass'));
    gulp.watch(filesJs, gulp.series('uglify'));
});

并使用

gulp.task('default', gulp.series('uglify', 'sass', 'watchFiles'));