学习node的gulp压缩项目文件时,出现错误:

[21:01:03] The following tasks did not complete: cssmin
[21:01:03] Did you forget to signal async completion?

出错原因

原因:gulp不再支持同步任务.因为同步任务常常会导致难以调试的细微错误,例如忘记从任务(task)中返回 stream。,所以必须在任务完成执行时发出信号(“异步完成”)。
在“Gulp3.x”中,你可以不做这个就离开。如果您没有显式地发出异步完成的信号,那么Gulp只会假定您的任务是同步的,并且一旦您的任务函数返回,它就完成了。Gulp4.x在这方面更严格。你必须明确地发出任务完成的信号。

当你看到 "Did you forget to signal async completion?" 警告时,说明你并未使用前面提到的返回方式。你需要使用 callback 或返回 stream、promise、event emitter、child process、observable 来解决此问题。具体详情请看API的异步执行

解决方法

1.将gulp版本回退

把版本重新安装3.9.1就可以快速解决(不推荐这种做法)

npm install --save-dev gulp@3.9.1

2.调用回调函数

对于我的用例来说,这是最简单的方法:gulp自动将回调函数作为第一个参数传递给我的任务。完成后调用该函数

代码示例:

gulp.task('htmlmin', () => {
	gulp.src('./src/*.html')
		.pipe(fileinclude())
		// 压缩html文件中的代码
		.pipe(htmlmin({ collapseWhitespace: true }))
		.pipe(gulp.dest('dist'));
});

更改为:

gulp.task('htmlmin', done => {
	gulp.src('./src/*.html')
		.pipe(fileinclude())
		// 压缩html文件中的代码
		.pipe(htmlmin({ collapseWhitespace: true }))
		.pipe(gulp.dest('dist'));
		done()
});

运行之后:

PS C:\Users\Shinelon\Documents\HBuilderProjects\前端学习\11-16 前后端交互\day01\code\gulp-demo> gulp htmlmin
[21:11:51] Using gulpfile ~\Documents\HBuilderProjects\前端学习\11-16 前后端交互\day01\code\gulp-demo\gulpfile.js
[21:11:51] Starting 'htmlmin'…
[21:11:51] Finished 'htmlmin' after 1