Gulp学习--css、htlm、js、image、less、scss文件压缩代码(可以直接写入gulpfile.js)

const { src,dest,task,watch,series,parallel } = require('gulp');
const cssnano = require('gulp-cssnano');
const sass = require('gulp-sass');
const less = require('gulp-less');
const uglify = require('gulp-uglify');
const htmlMin = require('gulp-htmlmin');
const imagemin = require('gulp-imagemin');
const cache = require('gulp-cache');
const sourcemaps = require('gulp-sourcemaps');
const rename = require('gulp-rename');

//压缩scss文件任务
task('scss', async function(){
	await src('./src/scss/*.scss')
		.pipe(sourcemaps.init())
		.pipe(sass())
		.pipe(cssnano({
			zindex:false
		}))
		.pipe(rename({
			suffix:'.min'
		}))
		.pipe(sourcemaps.write())
		.pipe(dest('./dist/css/'));
});

//压缩less文件任务
task('less', async function(){
	await src('./src/less/*.less')
		.pipe(sourcemaps.init())
		.pipe(less())
		.pipe(cssnano({
			zindex:false
		}))
		.pipe(rename({
			suffix:'.min'
		}))
		.pipe(sourcemaps.write())
		.pipe(dest('./dist/css/'));
});

//压缩css文件任务
task('css', async function(){
	await src('./src/**/*.css')		
		.pipe(sourcemaps.init())	
		.pipe(cssnano({			
			zindex:false		
		}))
		.pipe(rename({			
			'suffix': '.min'
		}))						
		.pipe(sourcemaps.write('.'))
		.pipe(dest('./dist/css/'));	
});

//压缩js文件任务
task('js', async function(){
	await src('./src/js/*.js')
		.pipe(sourcemaps.init())
		.pipe(uglify({
			parse: {
				html5_comments: true 	
    		},

    		compress: {
        		drop_console:false, 	
    		},
		    toplevel: false,	
		}))
		.pipe(rename({
			suffix:'.min',
		}))
		.pipe(sourcemaps.write('.'))
		.pipe(dest('./dist/js/'))
});

//压缩html文件任务
task('html', async function html(){
	await src('./src/html/*.html')
		.pipe(sourcemaps.init())
		.pipe(htmlMin({ 
			collapseWhitespace: true, 
			caseSensitive:false,
			removeTagWhitespace:false, 
		}))
		.pipe(rename({
			suffix:'.min'
		}))
		.pipe(sourcemaps.write())
		.pipe(dest('./dist/html/'));
});

//压缩图片文件任务
task('image', async function img() {
	await src('./src/image/*.*')
		.pipe(cache(imagemin([ 	
			imagemin.gifsicle({
				interlaced: true, 
				optimizationLevel:1,
			}),

			imagemin.mozjpeg({
				quality: 75, 	
				progressive: true,
			}),

			imagemin.optipng({
				optimizationLevel: 5,
				interlaced: false,
				errorRecovery:true,
			}),

			imagemin.svgo({
				plugins: [
					{removeViewBox: false}, 
					{cleanupIDs: false} 
				]
			})
		])))
		.pipe(dest('./dist/image'))
});

//监听css、js、html、image任务
task('watch', function(){
	watch('./src/css/*.css', series('css'));
	watch('./src/less/*.less', series('less'));
	watch('./src/scss/*.scss', series('scss'));
	watch('./src/js/*.js', series('js'));
	watch('./src/html/*.html', series('html'));
	watch('./src/image/*.{jpg,png,svg,gif}', series('image'));
});

//创建默认任务
task("default", parallel('watch'));

你可能感兴趣的:(gulp)