1.gulp-imagemin 压缩图片
var gulp = require('gulp'),
imagemin = require('gulp-imagemin');
gulp.task('testImagemin', function () {
gulp.src('src/img/*.{png,jpg,gif,ico}')
.pipe(imagemin({
optimizationLevel: 5, //类型:Number 默认:3 取值范围:0-7(优化等级)
progressive: true, //类型:Boolean 默认:false 无损压缩jpg图片
interlaced: true, //类型:Boolean 默认:false 隔行扫描gif进行渲染
multipass: true //类型:Boolean 默认:false 多次优化svg直到完全优化
}))
.pipe(gulp.dest('dist/img'));
});
深度压缩图片
var gulp = require('gulp'),
imagemin = require('gulp-imagemin'),
//确保本地已安装imagemin-pngquant [cnpm install imagemin-pngquant --save-dev]
pngquant = require('imagemin-pngquant');
gulp.task('testImagemin', function () {
gulp.src('src/img/*.{png,jpg,gif,ico}')
.pipe(imagemin({
progressive: true,
svgoPlugins: [{removeViewBox: false}],//不要移除svg的viewbox属性
use: [pngquant()] //使用pngquant深度压缩png图片的imagemin插件
}))
.pipe(gulp.dest('dist/img'));
});
只压缩修改的图片。压缩图片时比较耗时,在很多情况下我们只修改了某些图片,没有必要压缩所有图片,使用”gulp-cache”只压缩修改的图片,没有修改的图片直接从缓存文件读取(C:\Users\Administrator\AppData\Local\Temp\gulp-cache
)。
var gulp = require('gulp'),
imagemin = require('gulp-imagemin'),
pngquant = require('imagemin-pngquant'),
//确保本地已安装gulp-cache [cnpm install gulp-cache --save-dev]
cache = require('gulp-cache');
gulp.task('testImagemin', function () {
gulp.src('src/img/*.{png,jpg,gif,ico}')
.pipe(cache(imagemin({
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
})))
.pipe(gulp.dest('dist/img'));
});
gulp-htmlmin
使用gulp-htmlmin压缩html,可以压缩页面javascript、css,去除页面空格、注释,删除多余属性等操作
var gulp = require('gulp'),
htmlmin = require('gulp-htmlmin');
gulp.task('testHtmlmin', function () {
var options = {
removeComments: true,//清除HTML注释
collapseWhitespace: true,//压缩HTML
collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input />
removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
removeScriptTypeAttributes: true,//删除<script>的type="text/javascript"
removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
minifyJS: true,//压缩页面JS
minifyCSS: true//压缩页面CSS
};
gulp.src('src/html/*.html')
.pipe(htmlmin(options))
.pipe(gulp.dest('dist/html'));
});
gulp-minify-css【gulp-clean-css】
使用gulp-minify-css压缩css文件,减小文件大小,并给引用url添加版本号避免缓存。重要:gulp-minify-css已经被废弃,请使用gulp-clean-css,用法一致
1、基本使用
var gulp = require('gulp'),
cssmin = require('gulp-minify-css');
gulp.task('testCssmin', function () {
gulp.src('src/css/*.css')
.pipe(cssmin())
.pipe(gulp.dest('dist/css'));
});
2、gulp-minify-css 最终是调用clean-css
var gulp = require('gulp'),
cssmin = require('gulp-minify-css');
gulp.task('testCssmin', function () {
gulp.src('src/css/*.css')
.pipe(cssmin({
advanced: false,//类型:Boolean 默认:true [是否开启高级优化(合并选择器等)]
compatibility: 'ie7',//保留ie7及以下兼容写法 类型:String 默认:''or'*' [启用兼容模式; 'ie7':IE7兼容模式,'ie8':IE8兼容模式,'*':IE9+兼容模式]
keepBreaks: true,//类型:Boolean 默认:false [是否保留换行]
keepSpecialComments: '*'
//保留所有特殊前缀 当你用autoprefixer生成的浏览器前缀,如果不加这个参数,有可能将会删除你的部分前缀
}))
.pipe(gulp.dest('dist/css'));
});
3、给css文件里引用url加版本号(根据引用文件的md5生产版本号),像这样:
var gulp = require('gulp'),
cssmin = require('gulp-minify-css');
//确保已本地安装gulp-make-css-url-version [cnpm install gulp-make-css-url-version --save-dev]
cssver = require('gulp-make-css-url-version');
gulp.task('testCssmin', function () {
gulp.src('src/css/*.css')
.pipe(cssver()) //给css文件里引用文件加版本号(文件MD5)
.pipe(cssmin())
.pipe(gulp.dest('dist/css'));
});
3、若想保留注释,这样注释即可:
/*!
Important comments included in minified output.
*/
用gulp-rev-append给页面的引用添加版本号,清除页面引用缓存。
var gulp = require('gulp'),
rev = require('gulp-rev-append');
gulp.task('testRev', function () {
gulp.src('src/html/index.html')
.pipe(rev())
.pipe(gulp.dest('dist/html'));
});
配置html页面引用
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="css/style.css?rev=@@hash">
<script src="js/js-one.js?rev=@@hash"></script>
<script src="js/js-two.js"></script>
</head>
<body>
<div>hello, world!</div>
<img src="img/test.jpg?rev=@@hash" alt="" />
<script src="js/js-three.js?rev=@@hash"></script>
</body>
</html>
效果如下:
4.gulp-uglify
1、基本使用
var gulp = require('gulp'),
uglify = require('gulp-uglify');
gulp.task('jsmin', function () {
gulp.src('src/js/index.js')
.pipe(uglify())
.pipe(gulp.dest('dist/js'));
});
2、压缩多个js文件
var gulp = require('gulp'),
uglify = require('gulp-uglify');
gulp.task('jsmin', function () {
gulp.src(['src/js/index.js','src/js/detail.js']) //多个文件以数组形式传入
.pipe(uglify())
.pipe(gulp.dest('dist/js'));
});
3、匹配符“!”,“”,“*”,“{}”
var gulp = require('gulp'),
uglify= require('gulp-uglify');
gulp.task('jsmin', function () {
//压缩src/js目录下的所有js文件
//除了test1.js和test2.js(**匹配src/js的0个或多个子文件夹)
gulp.src(['src/js/*.js', '!src/js/**/{test1,test2}.js'])
.pipe(uglify())
.pipe(gulp.dest('dist/js'));
});
4、指定变量名不混淆改变
var gulp = require('gulp'),
uglify= require('gulp-uglify');
gulp.task('jsmin', function () {
gulp.src(['src/js/*.js', '!src/js/**/{test1,test2}.js'])
.pipe(uglify({
//mangle: true,//类型:Boolean 默认:true 是否修改变量名
mangle: {except: ['require' ,'exports' ,'module' ,'$']}//排除混淆关键字
}))
.pipe(gulp.dest('dist/js'));
});
5、gulp-uglify其他参数 具体参看
var gulp = require('gulp'),
uglify= require('gulp-uglify');
gulp.task('jsmin', function () {
gulp.src(['src/js/*.js', '!src/js/**/{test1,test2}.js'])
.pipe(uglify({
mangle: true,//类型:Boolean 默认:true 是否修改变量名
compress: true,//类型:Boolean 默认:true 是否完全压缩
preserveComments: 'all' //保留所有注释
}))
.pipe(gulp.dest('dist/js'));
});
5、gulp-concat合并javascript文件,减少网络请求。
var gulp = require('gulp'),
concat = require('gulp-concat');
gulp.task('testConcat', function () {
gulp.src('src/js/*.js')
.pipe(concat('all.js'))//合并后的文件名
.pipe(gulp.dest('dist/js'));
});
6.gulp-autoprefixer
使用gulp-autoprefixer根据设置浏览器版本自动处理浏览器前缀。使用她我们可以很潇洒地写代码,不必考虑各浏览器兼容前缀。【特别是开发移动端页面时,就能充分体现它的优势。例如兼容性不太好的flex布局。】
var gulp = require('gulp'),
autoprefixer = require('gulp-autoprefixer');
gulp.task('testAutoFx', function () {
gulp.src('src/css/index.css')
.pipe(autoprefixer({
browsers: ['last 2 versions', 'Android >= 4.0'],
cascade: true, //是否美化属性值 默认:true 像这样:
//-webkit-transform: rotate(45deg);
// transform: rotate(45deg);
remove:true //是否去掉不必要的前缀 默认:true
}))
.pipe(gulp.dest('dist/css'));
});
2、gulp-autoprefixer的browsers参数详解 (传送门):
● last 2 versions: 主流浏览器的最新两个版本
● last 1 Chrome versions: 谷歌浏览器的最新版本
● last 2 Explorer versions: IE的最新两个版本
● last 3 Safari versions: 苹果浏览器最新三个版本
● Firefox >= 20: 火狐浏览器的版本大于或等于20
● iOS 7: IOS7版本
● Firefox ESR: 最新ESR版本的火狐
● > 5%: 全球统计有超过5%的使用率
3、发现上面规律了吗,相信这不难看出,接下来说说各浏览器的标识:
Android for Android WebView.
BlackBerry or bb for Blackberry browser.
**Chrome **for Google Chrome.
Firefox or ff for Mozilla Firefox.
Explorer or ie for Internet Explorer.
iOS or ios_saf for iOS Safari.
Opera for Opera.
Safari for desktop Safari.
OperaMobile or op_mob for Opera Mobile.
OperaMini or op_mini for Opera Mini.
ChromeAndroid or and_chr
FirefoxAndroid or and_ff for Firefox for Android.
ExplorerMobile or ie_mob for Internet Explorer Mobile
7.有些 gulp 任务编译出错会终止 gulp.watch,使用 gulp-watch-path配合 stream-combiner2可避免这种情况。
gulp.watch('src/**/*', function (event) {
var paths = require('gulp-watch-path')(event, 'src/', 'dist/', 'node');
console.log(paths)
/*
paths {srcPath: 'src/file.js',
srcDir: 'src/',
distPath: 'dist/file.node',
distDir: 'dist/',
srcFilename: 'file.js',
distFilename: 'file.node' }
*/
gulp.src(paths.srcPath)
.pipe(uglify())
.pipe(gulp.dest(paths.distDir))
})
Throw an error::
var gulp = require('gulp')
var watchPath = require('gulp-watch-path')
var uglify = require('gulp-uglify')
var combiner = require('stream-combiner2')
gulp.task('default', function () {
gulp.watch('src/**/*.js', function (event) {
var paths = watchPath(event,'src/', 'dist/');
/*
paths
srcPath: 'src/file.js',
distDir: 'dist/'
*/
var combined = combiner.obj([
gulp.src(paths.srcPath), // src/file.js
uglify(),
gulp.dest(paths.distDir) // dist/
]);
combined.on('error', function (err) {
console.log('--------------')
console.log('Error')
console.log('fileName: ' + err.fileName)
console.log('lineNumber: ' + err.lineNumber)
console.log('message: ' + err.message)
console.log('plugin: ' + err.plugin)
})
console.log('\n')
console.log(event.type + ': ' + paths.srcPath)
console.log('dist: ' + paths.distPath)
/*
changed: src/file.js
dist: dist/file.js
*/
})
})
watchPath(event, search, replace, distExt)
event gulp.watch 回调函数的 event
search 需要被替换的起始字符串
replace 第三个参数是新的的字符串
distExt 扩展名(非必填)