1. gulp.task('default', ['htmlmin', 'cssmin', 'jsmin', 'copy']);
Will report an error:
This is the biggest change in Gulp 4 is that you can't pass a dependent task list as before. Therefore, you can no longer use Gulp3 to specify dependent tasks, you need to use gulp.series and gulp.parallel, because gulp tasks now only have two parameters
gulp.series: execute in sequence
gulp.paralle: can be calculated in parallel
The modified code is:
gulp.task('default',gulp.series('htmlmin', 'cssmin', 'jsmin', 'copy'));
Continue to report errors:
Solution:
In gulp4, you need to specify the end of the task . In gulp4
, you must tell gulp that our task has been completed. In gulp3, we don't need to do this, because if the asynchronous completion signal is not sent, then when the task returns, gulp will think it has been completed, and gulp4 must clearly indicate that the task is completed.
Another common way to tell gulp to complete a task is to return a stream or Promise:
Modify the code (return a stream for each task):
//告诉gulp任务完成的另一个常见方法是 返回(return) 一个流或者 Promise:
gulp.task('htmlmin', () => {
return gulp.src('./src/*.html')
.pipe(fileinclude())
//压缩html文件中的文件
.pipe(htmlmin({
collapseWhitespace: true}))
.pipe(gulp.dest('dist'));
});
Final code
//引用gulp模块
const gulp=require('gulp');
const htmlmin = require('gulp-htmlmin');
const fileinclude = require('gulp-file-include');
const csso = require('gulp-csso');
const less = require('gulp-less');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');
//使用gulp.task建立任务
//1使用任务的名称
//2任务的回调函数
gulp.task('first',()=>{
console.log("第一个gulp任务执行了")
//获取要处理文件
gulp.src('./src/css/base.css')
.pipe(gulp.dest('./dist/css'));
})
//html任务
//1html文件中代码的压缩操作
//2抽取html文件中的公共代码
gulp.task('htmlmin',()=>{
return gulp.src('./src/*.html')
.pipe(fileinclude())
//压缩html文件中的代码
.pipe(htmlmin({ collapseWhitespace: true }))
.pipe(gulp.dest('dist'));
})
//css任务
//1less语法转换
//2css代码压缩
gulp.task('cssmin',()=>{
//选择css目录下的所有less和css文件
return gulp.src(['./src/css/*.less','./src/css/*.css'])
// 将less语法转换成css
.pipe(less( ))
// 将css代码进行压缩
.pipe(csso())
// 将处理结果进行输出
.pipe(gulp.dest('./dist/css'))
})
//js任务
//1es6代码转换
//2代码压缩
gulp.task('jsmin',()=>{
return gulp.src('./src/js/*.js')
.pipe(babel({
//可以判断当前代码的运行环境 将代码转换成当前运行环境所支持的代码
presets: ['@babel/env']
}))
.pipe(uglify())
.pipe(gulp.dest('./dist/js'))
})
//复制文件夹
gulp.task('copy',()=>{
return gulp.src('./src/images/*')
.pipe(gulp.dest('dist/images'));
return gulp.src('./src/lib/*')
.pipe(gulp.dest('dist/lib'));
})
// 构建任务
gulp.task('default',gulp.series('htmlmin', 'cssmin', 'jsmin', 'copy'));