经历了gulp运行报错:Task function must be specified必须指定任务函数、gulp4.0报错The following tasks did not complete: default Did you forget to signal async completion?终于折腾出一个能用的gulp4.0构建任务实例,仅供参考:
一、新建package.json文件
{
"name": "test",
"version": "2.0.0",
"description": "gulp4任务构建",
"main": "gulpfile.js",
"scripts": {
"start": "gulp",
"build": "gulp build",
"clean": "gulp clean",
"cleanModule": "gulp cleanModule"
},
"author": "jinbo",
"license": "ISC",
"devDependencies": {
"del": "^4.1.0",
"es3ify-webpack-plugin": "^0.1.0",
"glob": "^7.1.3",
"gulp": "^4.0.0",
"gulp-autoprefixer": "^6.0.0",
"gulp-clean-css": "^4.0.0",
"gulp-connect": "^5.7.0",
"gulp-if": "^2.0.2",
"gulp-load-plugins": "^1.5.0",
"gulp-sass": "^4.0.2",
"gulp-smushit": "^1.2.0",
"gulp-util": "^3.0.8",
"swig-templates": "^2.0.3",
"through2": "^3.0.1",
"ts-loader": "^5.3.3",
"typescript": "^3.4.2",
"uglifyjs-webpack-plugin": "^2.1.2",
"webpack": "^4.29.6"
}
}
二、新建目录,cd到目录下,运行npm install安装
三、新建gulpfile.js文件
const {series,src,parallel,dest,watch} = require('gulp');
const $ = require('gulp-load-plugins')();
const swig = require('swig-templates');
const through = require('through2');
const path = require('path');
const glob = require('glob');
const webpack = require('webpack');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const es3ifyPlugin = require('es3ify-webpack-plugin');
const del = require('del');
// 编译Sass
function sass(){
return src('src/sass/!(reset|define|common).scss')
.pipe($.sass())
.pipe($.autoprefixer())
.pipe( $.if(process.env.production !== undefined, $.cleanCss({ compatibility:'ie7' })) )
.pipe(dest('build/css'))
.pipe($.connect.reload());
};
const swigParser = function(){
// 设置加载器
swig.setDefaults({
cache: false,// 禁用内存缓存
loader: swig.loaders.fs(),
});
return through.obj(function(file, enc, next){
let locals = {};
locals.file = path.parse(file.path);
// locals.Random = Mock.Random;
locals.makeArray = lenth=>new Array(lenth);
locals.production = 0;
if(process.env.production) locals.production = 1;
let content = file.contents.toString();
let html = '';
try{
html = swig.render(content, {filename: file.path, locals});
} catch(e){
this.emit('error', new $.util.PluginError('swig-parser', e.message));
}
file.contents = Buffer.from(html);
next(null, file);
});
}
function html(){
return src('src/[^_]*.html')
.pipe(swigParser())
.pipe(dest('build'))
.pipe($.connect.reload());
}
function image(){
return src('src/images/*.{jpg,png}')
.pipe($.if(process.env.production !== undefined, $.smushit()))//压缩图片非常慢,请耐心等待
.pipe(dest('build/images'))
.pipe($.connect.reload());
}
function temp(){
return src('src/temp/**/*.*')
.pipe($.if(process.env.production !== undefined, $.smushit()))//压缩图片非常慢,请耐心等待
.pipe(dest('build/temp'))
.pipe($.connect.reload());
}
function reloadJs(){
return src('src/**/**.ts')
.pipe($.connect.reload());
};
function js(cb){
const files = glob.sync('src/js/*.ts');
const entry = {};
files.forEach(filepath => {
const pathObj = path.parse(filepath);
entry[pathObj.name] = path.resolve(filepath);
});
const production = process.env.production !== undefined;
const plugins = [];
plugins.push(new es3ifyPlugin());
if (production) {
plugins.push(new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production'),
}));
plugins.push(new UglifyJSPlugin({
uglifyOptions: {
compress: {
properties:false
}
}
}));
}
webpack({
mode: 'none',
entry,
output: {
filename: '[name].js',
path: __dirname + '/build/js'
},
resolve: {
extensions: [".ts",".js", ".json"]
},
module: {
/* 在webpack2.0版本已经将 module.loaders 改为 module.rules 为了兼容性考虑以前的声明方法任然可用,
同时链式loader(用!连接)只适用于module.loader,
同时-loader不可省略 */
rules: [
{
test: /\.ts$/,
use: [
{
loader: "ts-loader"
}
],
exclude: /node_modules/
}
]
},
plugins
},(error, stats) => {
if (error) {
console.log(error);
} else if (stats.hasErrors()) {
console.log(stats.toString({
colors: true,
reasons: true,
}));
}
cb();//这个cb是为了解决gulp异步任务的核心,强烈注意
});
}
function assets(){
return src('src/lib/assets/*.*')
.pipe(dest('build'))
};
function server(cb){
$.connect.server({
root: 'build',
host: '0.0.0.0',
port: 8080,
livereload: true
});
cb();
}
function watchTask(){
watch('src/*.html',series(html));
watch('src/sass/*.scss',series(sass));
watch('src/images/*.*',series(image));
watch('src/temp/*.*', series(temp));
watch('src/**/*.ts',series(js,reloadJs));
};
function clean(cb){
process.env.production = true;
del('build').then(paths=>cb());
}
//gulp.series按顺序执行任务
//gulp.parallel最大并发性运行任务
exports.default = series(parallel(sass,html,image,temp,js,assets),series(server,watchTask));
exports.build = series(clean,parallel(sass,html,image,temp,js,assets),series(server,watchTask));
exports.clean = clean;
exports.cleanModule = cb=>{
del('node_modules').then(paths => cb());
};
四、npm run start运行