gulp 可以压缩静态资源 css,js,images ,通过gulp 可以让这些自动化,gulp 的 pipe 就像管道一样来处理静态资源。
gulp 的配置文件见后,完整的项目demo请访问: https://github.com/robertzhai/web_build/tree/master/gulp-practise
//gulpfile.js
// Include gulpfunction getDate() {var dateFormat = require('dateformat');var now = new Date();return dateFormat(now, "yyyyhhMMss");}
var date = getDate();
var gulp = require('gulp');//del older files
var del = require('del');
gulp.task('clean', function (cb) {del(['build/js','build/css','build/img',// 'build/mobile/**/*',// 我们不希望删掉这个文件,所以我们取反这个匹配模式// '!dist/mobile/deploy.json'], cb);
});//js
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
gulp.task('scripts', function() {return gulp.src('src/js/**/*')// .pipe(concat('main.js')).pipe(rename({suffix: '.' + date + '.min'})).pipe(uglify()).pipe(gulp.dest('build/js'));
});
// images
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');gulp.task('images', function() {return gulp.src('src/img/**/*').pipe(rename({suffix: '.' + date})).pipe(cache(imagemin({ optimizationLevel: 5, progressive: true, interlaced: true }))).pipe(gulp.dest('build/img'));
});// css
// 获取 minify-css 模块(用于压缩 CSS)
var minifyCSS = require('gulp-minify-css')
// 压缩 css 文件
// 在命令行使用 gulp css 启动此任务
gulp.task('css', function () {// 1. 找到文件gulp.src('src/css/**/*').pipe(rename({suffix: '.' + date + '.min'}))// 2. 压缩文件.pipe(minifyCSS())// 3. 另存为压缩文件.pipe(gulp.dest('build/css'))
})//watch
gulp.task('watch', function() {// Watch .js filesgulp.watch('src/js/**/*', ['scripts']);// Watch image filesgulp.watch('src/img/**/*', ['images']);// Watch css filesgulp.watch('src/css/**/*', ['css']);});// Default Task
// gulp.task('default', ['clean']);
gulp.task('default', ['clean', 'scripts', 'images', 'css', 'watch']);