/** * 1. LESS编译 压缩 合并 * 2. JS合并 压缩 混淆 * 3. img复制 * 4. html压缩 */
// 在gulpfile中先载入gulp包,因为这个包提供了一些API var gulp = require('gulp'); var less = require('gulp-less'); var cssnano = require('gulp-cssnano');
// 1. LESS编译 压缩 --合并没有必要,一般预处理CSS都可以导包 gulp.task('style', function() { // 这里是在执行style任务时自动执行的 gulp.src(['src/styles/*.less', '!src/styles/_*.less']) .pipe(less()) .pipe(cssnano()) .pipe(gulp.dest('dist/styles')) .pipe(browserSync.reload({ stream: true })); });
var concat = require('gulp-concat'); var uglify = require('gulp-uglify');
// 2. JS合并 压缩混淆 gulp.task('script', function() { gulp.src('src/scripts/*.js') .pipe(concat('all.js')) .pipe(uglify()) .pipe(gulp.dest('dist/scripts')) .pipe(browserSync.reload({ stream: true })); });
// 3. 图片复制 gulp.task('image', function() { gulp.src('src/images/*.*') .pipe(gulp.dest('dist/images')) .pipe(browserSync.reload({ stream: true })); });
var htmlmin = require('gulp-htmlmin'); // 4. HTML gulp.task('html', function() { gulp.src('src/*.html') .pipe(htmlmin({ collapseWhitespace: true, removeComments: true })) .pipe(gulp.dest('dist')) .pipe(browserSync.reload({ stream: true })); });
var browserSync = require('browser-sync'); gulp.task('serve', function() { browserSync({ server: { baseDir: ['dist'] }, }, function(err, bs) { console.log(bs.options.getIn(["urls", "local"])); });
gulp.watch('src/styles/*.less',['style']); gulp.watch('src/scripts/*.js',['script']); gulp.watch('src/images/*.*',['image']); gulp.watch('src/*.html',['html']); });
附录:
gulp常用插件:
gulp-less:编译less gulp-concat:合并代码 gulp-uglify:压缩js文件 gulp-rename:重命名文件 gulp-cssnano:css压缩 gulp-htmlmin:压缩html gulp-imagemin:压缩图像 brower-sync:用来代替创建服务器 gulp-connect:创建本地服务器