gulp 构建前端项目(一) gulp基础应用 是对gulp初次使用。
这篇文章主要介绍:
一.使用插件实现html, css, js的压缩。
二.图片压缩缓存,避免重复压缩。
三.浏览器同步刷新。包含监听文件变化。
1.文件压缩。
1)js压缩。安装,使用 gulp-uglify 插件。
在对js文件流处理增加uglify()操作。
var uglify = require('gulp-uglify');
gulp.src(jsPath)
.pipe(uglify(
-
mangle :true,//类型:Boolean 默认:true 是否修改变量名
-
compress:true,//类型:Boolean 默认:true 是否完全压缩
-
//preserveComments:'all' //保留所有注释 这个属性在3.0版本已经没有了
2)css压缩。安装,使用 gulp-clean-css 插件。
var stylemin = require('gulp-clean-css');
gulp.src(sourcePath)
.pipe(stylemin({
advanced: false,//类型:Boolean 默认:true [是否开启高级优化(合并选择器等)]
compatibility: 'ie9',//保留ie9及以下兼容写法 类型:String 默认:''or'*' [启用兼容模式; 'ie7':IE7兼容模式,'ie8':IE8兼容模式,'*':IE9+兼容模式]
keepBreaks: true,//类型:Boolean 默认:false [是否保留换行]
keepSpecialComments: '*'
//保留所有特殊前缀 当你用autoprefixer生成的浏览器前缀,如果不加这个参数,有可能将会删除你的部分前缀
}))
.pipe(gulp.dest(destPath))
3)html压缩。 安装,使用 gulp-htmlmin 插件。
var htmlmin = require('gulp-htmlmin');
var options = {
removeComments: true,//清除HTML注释
collapseWhitespace: true,//压缩HTML
collapseBooleanAttributes: false,//省略布尔属性的值 <input checked="true"/> ==> <input />
removeEmptyAttributes: false,//删除所有空格作属性值 <input id="" /> ==> <input />
removeScriptTypeAttributes: true,//删除<script>的type="text/javascript"
removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
minifyJS: true,//压缩页面JS
minifyCSS: true//压缩页面CSS
};
return gulp.src(sourcePath.html.src)
.pipe(htmlmin(options))
.pipe(gulp.dest(sourcePath.basePath + sourcePath.html.emit))
2.图片压缩,使用 gulp-imagemin , 缓存使用 gulp-cache
在对图片imagemin处理之前,先使用cache处理一下,可以跳过没有修改的图片。
var imagemin = require('gulp-imagemin'); var cache = require('gulp-cache');
gulp.src(sourcePath.img.src)
.pipe(cache(imagemin({
optimizationLevel: 3, //类型:Number 默认:3 取值范围:0-7(优化等级)
progressive: true, //类型:Boolean 默认:false 无损压缩jpg图片
interlaced: true, //类型:Boolean 默认:false 隔行扫描gif进行渲染
})))
.pipe(gulp.dest(sourcePath.basePath + sourcePath.img.emit))
3.使用 gulp.watch(path, task) 可以监听文件的变化。并执行task任务(可以是任务数组)。
gulp.task('watch', function(cb) {
gulp.watch('js/*.*', ['scriptMinify']);
gulp.watch('css/*.*', ['styleMinify']);
gulp.watch('views/*.*', ['html']);
}) //监听html, css, js变化。并压缩处理。
浏览器实时更新。使用 browser-sync 插件。
var browserSync = require('browser-sync');
gulp.task('server', [],function () {
// 从这个项目的根目录启动服务器
browserSync.init({
server: {
baseDir: "./",
}
});
gulp.watch("css/*.css", ['styleMinify']); //实时更新到浏览器, 在 css流输出到文件前 .pipe(browserSync.reload({stream:true}))
gulp.watch('js/*.js', ['scriptMinify']); //添加实时更新到浏览器。在 js流输出之前 .pipe(browserSync.reload({stream:true}))
gulp.watch("views/*.html").on("change", browserSync.reload); //html修改,直接刷新页面。
})
在控制台,启动server任务时(gulp server)启动的是 http://localhost:3000/ 并没有到具体的页面,所以是个空页面。需要手动改到自己的 html 路径 :http://localhost:3000/views/login.html 这应该是不对的,暂时没找到解决办法。
欢迎在评论区留言,给出建议和意见。初尝gulp,不喜勿喷