首页 > 解决方案 > 如何让 Gulp 4 不多次运行单个任务?

问题描述

我有两个任务。他们有一个共同的任务,应该在任务之前执行。

使用Gulp 3,我以这种方式实现它们:

gulp.task('compile', () => {
    // Compiling the TypeScript files to JavaScript and saving them on disk
});

gulp.task('test', ['compile'], () => {
    // Running tests with the compiled files
});

gulp.task('minify', ['compile'], () => {
    // Minifying the compiled files using Uglify
});

guls.task('default', ['test', 'minify']);

当我运行任务时只运行 1 次gulp defaultcompile

Gulp 4中,我以这种方式实现它们:

gulp.task('compile', () => {
    // Compiling the TypeScript files to JavaScript and saving them on disk
});

gulp.task('test', gulp.series('compile', () => {
    // Running tests with the compiled files
}));

gulp.task('minify', gulp.series('compile', () => {
    // Minifying the compiled files using Uglify
}));

guls.task('default', gulp.parallel('test', 'minify'));

当我运行任务时gulp defaultcompile它会运行 2 次,这是不可取的,因为已经完成了一项备用工作。如何使任务只运行 1 次,保持独立运行testminify任务的能力?

标签: javascriptgulpgulp-4

解决方案


由于您正在尝试并行运行 test 和 minify,因此无法仅使 run 编译一次,因为它将成为顺序操作。你可以这样做,

gulp.task('compile', () => {
    // Compiling the TypeScript files to JavaScript and saving them on disk
});

gulp.task('test',() => {
    // Running tests with the compiled files
}));

gulp.task('minify',=> {
    // Minifying the compiled files using Uglify
}));

gulp.task('compile-and-test', gulp.series('compile','test'));

gulp.task('compile-and-minify', gulp.series('compile','minify'));

guls.task('default', gulp.series('compile', gulp.parallel('test', 'minify'));

这种方法将允许您运行单个操作,并使测试和缩小操作并行,同时只执行一次编译。

您可以在此处阅读更多详细信息。


推荐阅读