'use strict';
var gulp = require('gulp');
// browser sync
var browserSync = require('browser-sync');
var reload = browserSync.reload;
//rename
var rename = require('gulp-rename');
//sass
var sass = require('gulp-sass');
//add prefix
var autoprefixer = require('gulp-autoprefixer');
var cssnano = require('gulp-cssnano');
//compile sass
gulp.task('sass', function() {
gulp.src('src/sass/**/*.scss')
.pipe(sass()) //编译sass文件1
.pipe(autoprefixer()) // 自动加前缀
.pipe(cssnano()) //优化css代码
.pipe(rename({ extname: '.css' })) //更换名字
.pipe(gulp.dest('./src/css')); //放到css文件中
});
//html compress
var htmlmin = require('gulp-htmlmin');
gulp.task('html', function() {
gulp.src('./src/*.html')
.pipe(htmlmin({
collapseWhitespace: true, //压缩html
removeComments: true, //清楚注释
collapseBooleanAttributes: true, //省略布尔属性的值
removeEmptyAttributes: true, //删除所有空格作属性值
minifyJS: true, //压缩页面JS
minifyCSS: true //压缩页面CSS
}))
.pipe(gulp.dest('./dist'))
.pipe(reload({
stream: true
}));
});
//js 合并 压缩混淆
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
gulp.task('script', function() {
gulp.src('./src/js/*.js')
.pipe(concat('all.js'))
.pipe(uglify())
.pipe(gulp.dest('./dist/js'))
.pipe(reload({
stream: true
}));
});
//深度压缩 图片
var imagemin = require('gulp-imagemin'),
pngquant = require('imagemin-pngquant'),
//当某些图片文件发生改变时,只压缩改变的图片
cache = require('gulp-cache');
gulp.task('image', function() {
gulp.src('src/images/*.*')
.pipe(cache(imagemin({
progressive: true,
svgoPlugins: [{ removeViewBox: false }],
use: [pngquant()]
})))
.pipe(gulp.dest('dist/images'));
});
gulp.task('task', function() {
browserSync.init({
server: {
baseDir: './src/',
index: 'index.html'
},
open: 'external', //external 内网访问 local 本地访问(默认本地访问)
port: 8081
});
gulp.watch('./src/js/*.js', ['script']);
gulp.watch('./src/*.html', ['html']);
gulp.watch('./src/sass/**/*.scss', ['sass']);
gulp.watch('./src/**/*.html').on('change', reload);
gulp.watch('./src/**/*.css').on('change', reload);
gulp.watch('./src/**/*.js').on('change', reload);
})