1. gulp简介
gulp是一个前端自动化构建工具,主要用来设定程序自动处理静态资源的工作。
使用gulp,可以轻松实现对html,css,js进行压缩的目的。产品发布时,可以有效缩小代码大小。
2. gulp安装
gulp是nodejs的一个工具,因此可以使用npm进行安装。
$npm install gulp
3. gulpfile.js
在前端项目的根目录,通过编写gulpfile.js,控制gulp的运行。
4. 使用gulp压缩html
删除无用的空格,删除html中的注释等
var options = {
collapseWhitespace: true,
collapseBooleanAttributes: true,
removeComments: true,
removeEmptyAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
minifyJS: true,
minifyCSS: true
};
gulp.src('src/**/*.html')
.pipe(htmlmin(options))
.pipe(gulp.dest('dest/'));
5. 使用gulp,压缩css
gulp.src('src/**/*.css')
.pipe(minifycss())
.pipe(gulp.dest('dest'));
6. 使用gulp,压缩js
gulp.src('src/**/*.js')
.pipe(uglify({
mangle: false
}))
.pipe(gulp.dest('dest'));
7. 完整gulpfile.js文件
var gulp = require('gulp');
var htmlmin = require('gulp-htmlmin');
var uglify = require('gulp-uglify');
var minifycss = require('gulp-minify-css');
function build_html(cb) {
var options = {
collapseWhitespace: true,
collapseBooleanAttributes: true,
removeComments: true,
removeEmptyAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
minifyJS: true,
minifyCSS: true
};
gulp.src('src/**/*.html')
.pipe(htmlmin(options))
.pipe(gulp.dest('dest/'));
cb();
}
function build_js(cb) {
gulp.src('src/**/*.js')
.pipe(uglify({
mangle: false
}))
.pipe(gulp.dest('dest'));
cb();
}
function build_css(cb) {
gulp.src('src/**/*.css')
.pipe(minifycss())
.pipe(gulp.dest('dest'));
cb();
}
exports.default = gulp.parallel(build_html, build_js, build_css);