const gulp = require('gulp'); const fs = require('fs'); const htmlmin = require('gulp-htmlmin'); const uglify = require('gulp-uglify'); const uglifyEs = require('uglify-es'); const minifyCSS = require('gulp-minify-css'); const imagemin = require('gulp-imagemin'); const babel = require('gulp-babel'); const replace = require('gulp-replace'); const version = new Date().getTime(); /** * 清空 */ function clear(dist = 'dist') { if (fs.existsSync(dist)) { console.log("清空"); fs.rmSync(dist, { recursive: true }); } } function compressHtml(src, base = 'src', dist = 'dist') { gulp.src(src, { base: base, allowEmpty: true }) .pipe(replace('199210103019', version + '')) .pipe(replace(/(<link\s+.+\.css\?[^\"]+)/gi, '$1&zqd=' + version)) .pipe(replace(/(<link\s+.+\.css)\"/gi, '$1?zqd=' + version + '"')) .pipe(replace(/(<script\s+.+\.js\?[^\"]+)/gi, '$1&zqd=' + version)) .pipe(replace(/(<script\s+.+\.js)\"/gi, '$1?zqd=' + version + '"')) .pipe(htmlmin({ removeComments: true, collapseWhitespace: true, minifyCSS: true, minifyJS: file => uglifyEs.minify(file, { mangle: true }).code })) .pipe(gulp.dest(dist)); } function compressJs(src, base = 'src', dist = 'dist') { gulp.src(src, { base: base, allowEmpty: true }) .pipe(replace('199210103019', version + '')) .pipe(babel()) .pipe(uglify({ mangle: { toplevel: true }, output: { ascii_only: true } })) .pipe(gulp.dest(dist)); } function compressCss(src, base = 'src', dist = 'dist') { gulp.src(src, { base: base, allowEmpty: true }) .pipe(minifyCSS()) .pipe(gulp.dest(dist)); } function compressImage(src, base = 'src', dist = 'dist') { gulp.src(src, { base: base }) .pipe(imagemin({ optimizationLevel: 5, progressive: true, webp: { quality: 75 }, pngquant: { quality: '60-80' }, svgoPlugins: [{ removeViewBox: false }] })) .pipe(gulp.dest(dist)); } /** * 复制源目录到发布目录 * @param {string} src 源目录 * @param {string} dist 发布目录 */ function cp2Dist(src, dist = 'dist') { if (typeof (src) === 'string') { fs.cpSync(src, dist + '/' + src, { recursive: true }); } else { for (var s of src) { fs.cpSync(s, dist + '/' + s, { recursive: true }); } } } /** * 打包发布 */ async function release(cb) { await clear(); await cp2Dist(['favicon.ico', 'layuiadmin', 'views']); compressHtml([ '*.html', 'views/*.html', 'views/**/*.html'], '.'); compressJs(['layuiadmin/*.js', 'layuiadmin/modules/*.js', 'layuiadmin/lib/*.js', '!layuiadmin/layui/*.js', 'layuiadmin/lib/**/echartsTheme.js'], '.'); compressCss([ 'layuiadmin/style/*.css', 'layuiadmin/style/system/*.css', 'layuiadmin/style/system/ztree/awesomeStyle/layuiAwesome.css'], '.'); compressImage([ 'layuiadmin/images/*', 'layuiadmin/style/res/*'], '.'); console.log("完成打包"); return cb(); }; //清空 gulp.task('clear', () => clear()); //打包发布 gulp.task('release', release); gulp.task('default', release);
标签:src,layuiadmin,dist,pipe,压缩,js,gulp,base From: https://www.cnblogs.com/HelloCreator/p/17513106.html