[英]Set a Gulp task to be the default
我的gulpFile
有以下任务,由我团队中的其他人创建:
gulp.task('serve', [], function(){
gulp.run(
'fonts',
'browsersync',
'watch'
);
});
我想不管它,但我也想将默认任务映射到这个任务。 所以我试过:
gulp.task('default',['serve']);
它似乎工作,因为服务器运行,但由于某种原因“观察”任务没有发生,我没有在更改时刷新浏览器。
如果我运行“gulp serve”而不是“gulp”,一切都会按计划进行。 我做错了什么?
编辑:这是监视任务:
gulp.task('watch', ['styles', 'browsersync'], function() { //'default'
gulp.watch(
[
'./app/assets/sass/**/*.scss',
'./app/modules/**/*.scss'
], ['styles']);
gulp.watch([
'./app/**/*.js',
'./app/**/*.html'
], function() {
reload();
});
});
尝试更新您的默认任务以将 watch 任务包含在数组参数中,而不是在serve
中运行它。 像这样:
gulp.task('default', ['serve', 'watch']);
如果您查看有关异步任务支持的 Gulp 文档,尤其是最后一个示例,您将看到您可以要求在指定任务应该开始之前完成依赖任务。
var gulp = require('gulp');
// takes in a callback so the engine knows when it'll be done
gulp.task('one', function(cb) {
// do stuff -- async or otherwise
cb(err); // if err is not null and not undefined, the run will stop, and note that it failed
});
// identifies a dependent task must be complete before this one begins
gulp.task('two', ['one'], function() {
// task 'one' is done now
});
gulp.task('default', ['one', 'two']);
gulp.run
和gulp.start
被认为是不好的做法:
https://github.com/gulpjs/gulp/issues/426
https://github.com/gulpjs/gulp/issues/505
不幸的是,这里的答案似乎是您的同事可能并不真正了解 Gulp。 如果不更改他们的代码,您可能无法解决此问题。
没有更多上下文,就像整个 gulpfile 一样,我无法重现您的确切问题。 然而,我的预感是它与 Gulp 异步/连续运行任务的方式有关。 可能是您的“默认”任务过早退出,因为gulp.run
不会同步执行。 无论如何,Gulp 对哪些任务需要等待什么、何时等待感到困惑。 您正在使用两种完全不同的工具来管理您的运行序列。
而不是gulp.run
,您的“服务”任务应该真正使用依赖项来运行其他任务:
gulp.task('serve', ['fonts', 'browsersync', 'watch']);
gulp.task('default', ['serve']);
此外,值得指出的是,您的监视任务已经将“浏览器同步”列为依赖项。 虽然在技术上不是错误的(Gulp 第二次会忽略它),但它可能会导致过度复杂化和混乱,因此可能不是一个好主意。 如果 'watch' 依赖于 'browsersync',你可以从 'serve' 中删除 'browsersync' 依赖:
gulp.task('watch', ['styles', 'browsersync'], function () {
gulp.watch([
'./app/assets/sass/**/*.scss',
'./app/modules/**/*.scss'
], ['styles']);
gulp.watch([
'./app/**/*.js',
'./app/**/*.html'
], function() {
reload();
});
});
gulp.task('serve', ['fonts', 'watch']);
gulp.task('default', ['serve']);
这应该会让你得到你正在寻找的结果。
话虽如此,如果你真的坚持遵循不好的做法,你可以尝试在你的“默认”任务中使用gulp.run
:
gulp.task('default', function() {
gulp.run('serve');
});
我怀疑您的主要问题是您正在混合使用数组任务依赖项和gulp.run
,但无论哪种方式, gulp.run
都是“做错了”。
在 Gulp 版本 4 中测试,您可以像这样运行:
请注意,您可以使用 async 返回该函数。
文件名:gulpfile.js
gulp.task('one', async () => {
// action you desire
});
// If you want to in parallel
gulp.task('default', gulp.parallel('one'));
// If you want to in series
gulp.task('default', gulp.series('one'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.