Hello EWEN

gulp 常用配置

整理了网站开发中常用的 gulp 配置

package.json 依赖列表

{
  "name": "ewenConfig",
  "description": "ewen product",
  "version": "0.9.0",
  "author": "ewen",

  "devDependencies": {
    "gulp": "*",
    "gulp-concat": "*",
    "gulp-uglify": "*",
    "gulp-rename": "*",

    "del": "*",
    "gulp-livereload": "*",

    "gulp-autoprefixer": "*",
    "gulp-htmlmin": "*",
    "gulp-clean-css": "*",
    "gulp-sourcemaps": "*"
  }
}

gulpfile.js 配置

// 引入 gulp & 组件
var gulp = require('gulp');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');

//var notify = require('gulp-notify');
var del = require('del');

//var sass = require('gulp-sass');
//var less = require('gulp-less');

//var minifyHTML = require('gulp-minify-html');  //代码压缩
var htmlmin = require('gulp-htmlmin');  //代码压缩
var cleanCSS = require('gulp-clean-css');
var prefix = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');

var livereload = require('gulp-livereload');  //livereload插件

// 合并文件之后压缩代码
gulp.task('minify', function () {
    return gulp.src(['src/js/easeljs/*.min.js', 'src/js/common.js', 'src/js/lottery.js', 'js/lottery_main.js'])
        .pipe(sourcemaps.init())
        .pipe(concat('main.js'))
        //.pipe(gulp.dest('src/js'))
        //.pipe(rename('main.js'))
        //.pipe(uglify({compress: {drop_console: true}}))
        .pipe(uglify())
        .pipe(sourcemaps.write('../maps'))
        .pipe(gulp.dest('dist/js'));
});

//压缩HTML
//collapseWhitespace:删除空格   removeComments:删除注释  preserveLineBreaks:保持原行样式
gulp.task('minify-html', function () {
    var opts = {collapseWhitespace: true, removeComments: true, preserveLineBreaks: true};
    gulp.src('src/*.html')
        .pipe(htmlmin(opts))
        .pipe(gulp.dest('dist/'))
});

//压缩CSS
gulp.task('minify-css', function () {
    return gulp.src('src/css/*.css')
        .pipe(sourcemaps.init())
        .pipe(cleanCSS())
        .pipe(sourcemaps.write('../maps'))
        .pipe(gulp.dest('dist/css'));
});

//删除文件
gulp.task('clean', function (cb) {
    del(['dist/css', 'dist/js', 'dist/images'], cb)
});

// 监视文件的变化
gulp.task('watch', function () {
    gulp.watch('php/css_src/**/*.css', ['concat-css']);
    //gulp.watch('src/scss/**/*.scss', ['sass']);
    //gulp.watch('src/images/**/*', ['images']);

    //livereload.listen();
    //gulp.watch('dist/**').on('change', livereload.changed);
});

// 注册缺省任务
gulp.task('css', ['minify-css']);
gulp.task('default', ['minify', 'minify-css']);
gulp.task('debug', ['minify', 'watch']);

gulp安装与执行

npm install -g gulp-cli         //gulp安装

gulp    //gulp执行默认命令  或 gulp minify