求一份比较全面的gulp的配置文件

学习gulp, 求各位高手的配置, 看看都用什么插件,参考学习。

学习了一段时间。自己近期收集的

var gulp = require('gulp');
var del = require('del');
var rev = require('gulp-rev');
var nano = require('gulp-cssnano');
var uglify = require('gulp-uglify')
var useref = require('gulp-useref');
var imagemin = require('gulp-imagemin');
var revCollector = require('gulp-rev-collector');
var browserSync = require('browser-sync').create();
var gulpSequence = require('gulp-sequence');
var uncss = require('gulp-uncss');
var htmlmin = require('gulp-htmlmin');
var base64 = require('gulp-base64');
var changed = require('gulp-changed');
var postcss = require("gulp-postcss");
var sprites = require('postcss-sprites').default;
var autoprefixer = require('autoprefixer');
var cssgrace = require('cssgrace');

var SRC_DIR = './src/';
var PKG_DIR = './tmp/pkg/';
var REV_DIR = './tmp/rev/';
var DST_DIR = './dist/';
var UNCSS_REG = [/.advise/, /.block/, /.g-bd .m-view-2 .category li:nth-child/, /^.g-bd ul li .info/, /.hljs/];

gulp.task('clean', function() {
    return del(['dist', 'tmp']);
});

/*
 * 合并请求
 * <!-- build:css ../css/index.pkg.css --><!-- endbuild -->
 * <!-- build:js ../js/index.pkg.js --><!-- endbuild -->
 */
gulp.task('pkg', function() {
    return gulp.src(SRC_DIR + 'view/*.html')
        .pipe(useref())
        .pipe(gulp.dest(PKG_DIR + 'view/'));
});

/*
 * 移动非jpg/png资源到img文件夹
 * 
 */
gulp.task('move-img-other', function() {
    return gulp.src([SRC_DIR + 'img/**/*.*!(jpg|png)', SRC_DIR + 'component/img/**/*.*!(jpg|png)'])
        .pipe(gulp.dest('./tmp/pkg/img/'));
});

/*
 * 压缩IMG
 * 
 */
gulp.task('min-img', function() {
    return gulp.src([SRC_DIR + 'img/**/*.*(jpg|png)', SRC_DIR + 'component/img/**/*.*(jpg|png)'])
        .pipe(imagemin())
        .pipe(gulp.dest('./tmp/pkg/img/'));
});

/*
 * 压缩CSS(PC)
 * 
 */
gulp.task("min-css-pc", function() {
    // PostCSS
    var processors = [
        sprites({
            'stylesheetPath': PKG_DIR + 'css/',
            'spritePath': PKG_DIR + 'img/'
        }),
        autoprefixer({
            browsers: ['> 1%', 'last 2 versions', 'ie 6-11']
        }),
        cssgrace
    ];
    return gulp.src([PKG_DIR + 'css/**/*.css'])
        .pipe(uncss({
            html: [PKG_DIR + '**/*.html'],
            ignore: UNCSS_REG
        })).pipe(nano({
            discardComments: {
                removeAll: true
            }
        }))
        .pipe(postcss(processors))
        .pipe(gulp.dest(PKG_DIR + 'css/'))
});

/*
 * 压缩CSS(Mobile)
 * 
 */
gulp.task("min-css-mobile", function() {
    // PostCSS
    var processors = [
        autoprefixer({
            browsers: ['> 1%', 'last 2 versions']
        })
    ];
    return gulp.src([PKG_DIR + 'css/**/*.css'])
        .pipe(uncss({
            html: [PKG_DIR + '**/*.html'],
            ignore: UNCSS_REG
        })).pipe(nano({
            discardComments: {
                removeAll: true
            }
        }))
        .pipe(postcss(processors))
        .pipe(gulp.dest(PKG_DIR + 'css/'))
});

/*
 * 压缩JS
 * 
 */
gulp.task('min-js', function() {
    return gulp.src(PKG_DIR + 'js/**/*.js')
        .pipe(uglify())
        .pipe(gulp.dest(PKG_DIR + 'js/'));
});

/*
 * 版本化IMG
 * 
 */
gulp.task('rev-img', function() {
    return gulp.src(PKG_DIR + 'img/**/*')
        .pipe(rev())
        .pipe(gulp.dest(REV_DIR + 'img/'))
        .pipe(rev.manifest())
        .pipe(gulp.dest(REV_DIR + 'img/'));
});

/*
 * 版本化CSS
 * 
 */
gulp.task('rev-css', function() {
    return gulp.src(PKG_DIR + 'css/**/*')
        .pipe(rev())
        .pipe(gulp.dest(REV_DIR + 'css/'))
        .pipe(rev.manifest())
        .pipe(gulp.dest(REV_DIR + 'css/'));
});

/*
 * 版本化JS
 * 
 */
gulp.task('rev-js', function() {
    return gulp.src(PKG_DIR + 'js/**/*')
        .pipe(rev())
        .pipe(gulp.dest(REV_DIR + 'js/'))
        .pipe(rev.manifest())
        .pipe(gulp.dest(REV_DIR + 'js/'));
});

/*
 * 收集图片到CSS
 */
gulp.task('col-css', function() {
    return gulp.src([REV_DIR + 'img/*.json', REV_DIR + 'css/*.css'])
        .pipe(revCollector())
        .pipe(gulp.dest(DST_DIR + 'css/'));
});

/*
 * 移动IMG文件到目标文件夹
 */
gulp.task('col-img', function() {
    return gulp.src([REV_DIR + 'img/*', '!' + REV_DIR + '/img/*.json'])
        .pipe(gulp.dest(DST_DIR + 'img/'));
});

/*
 * 移动JS文件到目标文件夹
 */
gulp.task('col-js', function() {
    return gulp.src(REV_DIR + 'js/*.js')
        .pipe(gulp.dest(DST_DIR + 'js/'));
});

/*
 * 收集资源到HTML
 */
gulp.task('col-html', function() {
    return gulp.src([REV_DIR + '**/*.json', PKG_DIR + 'view/*.html'])
        .pipe(revCollector())
        .pipe(htmlmin({
            // collapseWhitespace: true,
            removeComments: true
        }))
        .pipe(gulp.dest(DST_DIR + 'view/'));
});

/*
 * 移动mock文件夹
 */
gulp.task('move-mock', function() {
    return gulp.src(SRC_DIR + 'mock/**/*')
        .pipe(gulp.dest(DST_DIR + 'mock/'));
});

/*
 * 图片base64
 */
gulp.task('base64', function() {
    return gulp.src(PKG_DIR + '/**/*.css')
        .pipe(base64({
            extensions: ['svg', 'png', /\.jpg#datauri$/i],
        }))
        .pipe(gulp.dest(PKG_DIR));
});


/*
 * 静态服务器
 */
gulp.task('bs', function() {
    browserSync.init({
        files: "**", //监听整个项目
        open: "external",
        server: {
            baseDir: "./dist/",
            index: 'view/index.html'
        }
    });
});

/*
 * 静态服务器(代理)
 */
gulp.task('bsp', function() {
    browserSync.init({
        proxy: "127.0.0.1"
    });
});

/*
 * PC打包方案
 */
gulp.task('pc', gulpSequence(
    'clean', 'pkg', 'min-img', 
    ['min-img', 'min-css-pc', 'min-js'], 'move-img-other', 
    ['rev-img', 'rev-css', 'rev-js'], 
    ['col-img', 'col-css', 'col-js', 'col-html'],
    'move-mock', 'bs'
));

/*
 * Mobile打包方案
 */
gulp.task('mobile', gulpSequence(
    'clean', 'pkg', 'min-img', 'base64', 'move-img-other',
    ['min-img', 'min-css-mobile', 'min-js'], 
    ['rev-img', 'rev-css', 'rev-js'], 
    ['col-img', 'col-css', 'col-js', 'col-html'],
    'move-mock', 'bs'
));


gulp.task('default', ['mobile'], function() {
    return del(['tmp/']);
});
阅读 17.4k
8 个回答

也是初学,互相学习~~

/*jshint node: true*/

//引入gulp及各种组件;

var gulp = require('gulp'),

    uglify = require('gulp-uglify'),

    minifyCSS = require('gulp-minify-css'),

    sass = require('gulp-sass'),

    imagemin = require('gulp-imagemin'),

    imageminJpegRecompress = require('imagemin-jpeg-recompress'),

    imageminOptipng = require('imagemin-optipng'),

    browserSync = require('browser-sync').create();


//设置各种输入输出文件夹的位置;

var srcScript = '../src/js/*.js',

    dstScript = '../dist/js',

    srcCss = '../src/css/*.css',

    dstCSS = '../dist/css',

    srcSass = '../src/css/*.scss',

    dstSass = '../dist/css',

    srcImage = '../src/img/*.*',

    dstImage = '../dist/img',

    srcHtml = '../src/*.html',

    dstHtml = '../dist';


//处理JS文件:压缩,然后换个名输出;

//命令行使用gulp script启用此任务;

gulp.task('script', function() {

    gulp.src(srcScript)

        .pipe(uglify())

        .pipe(gulp.dest(dstScript));

});


//处理CSS文件:压缩,然后换个名输出;

//命令行使用gulp css启用此任务;

gulp.task('css', function() {

    gulp.src(srcCss)

        .pipe(minifyCSS())

        .pipe(gulp.dest(dstCSS));

});


//SASS文件输出CSS,天生自带压缩特效;

//命令行使用gulp sass启用此任务;

gulp.task('sass', function() {

    gulp.src(srcSass)

        .pipe(sass({

            outputStyle: 'compressed'

        }))

        .pipe(gulp.dest(dstSass));

});


//图片压缩任务,支持JPEG、PNG及GIF文件;

//命令行使用gulp jpgmin启用此任务;

gulp.task('imgmin', function() {

    var jpgmin = imageminJpegRecompress({

            accurate: true,//高精度模式

            quality: "high",//图像质量:low, medium, high and veryhigh;

            method: "smallfry",//网格优化:mpe, ssim, ms-ssim and smallfry;

            min: 70,//最低质量

            loops: 0,//循环尝试次数, 默认为6;

            progressive: false,//基线优化

            subsample: "default"//子采样:default, disable;

        }),

        pngmin = imageminOptipng({

            optimizationLevel: 4

        });

    gulp.src(srcImage)

        .pipe(imagemin({

            use: [jpgmin, pngmin]

        }))

        .pipe(gulp.dest(dstImage));

});


//把所有html页面扔进dist文件夹(不作处理);

//命令行使用gulp html启用此任务;

gulp.task('html', function() {

    gulp.src(srcHtml)

        .pipe(gulp.dest(dstHtml));

});


//服务器任务:以dist文件夹为基础,启动服务器;

//命令行使用gulp server启用此任务;

gulp.task('server', function() {

    browserSync.init({

        server: "../dist"

    });

});


//监控改动并自动刷新任务;

//命令行使用gulp auto启动;

gulp.task('auto', function() {

    gulp.watch(srcScript, ['script']);

    gulp.watch(srcCss, ['css']);

    gulp.watch(srcSass, ['sass']);

    gulp.watch(srcImage, ['imgmin']);

    gulp.watch(srcHtml, ['html']);

    gulp.watch('../dist/**/*.*').on('change', browserSync.reload);

});


//gulp默认任务(集体走一遍,然后开监控);

gulp.task('default', ['script', 'css', 'sass', 'imgmin', 'html', 'server', 'auto']);

最近准备入PostCSS的坑……

也是初学者,互相学习。。。下面的代码,是用于对项目进行css、js合并,再进行压缩,添加上版本号标识。同时处理前端资源中的文件拷贝的问题。

var gulp = require('gulp'),                         //基础库
    clean = require('gulp-clean');                  //清空文件夹
    cssmin = require('gulp-minify-css'),            //css压缩
    uglify= require('gulp-uglify'),                 //js压缩
    rev = require('gulp-rev'),                      //更改版本号
    revCollector = require('gulp-rev-collector'),   //gulp-rev的插件,用于html模板更改引用路径
    jshint = require('gulp-jshint'),                //js静态代码检查
    replace = require('gulp-replace'),
    concat = require('gulp-concat');                //合并文件


//要合并的js文件
var xk_jsArray = [
        'src/js/jquery.pin.js',
        'src/js/swiper/swiper.jquery.min.js',
        'src/js/xk-layer.js',
        'src/js/xk-searchSelect.js',
        'src/js/xk-tagSearchSelect.js',
        'src/js/fileUploader/xk-uploadFile.js',
        'src/js/loading/loading.js',
        'src/js/instant_reminder.js',
        'src/js/submit-button-control.js',
        'src/js/move_box.js',
        'src/js/user/loginout.js',
        'src/js/totop.js',
        'src/js/tagsConfiguration.js',
        'src/js/infoLayer.js'
    ];

var websocket_jsArray = [
    'src/js/imengine.js',
    'src/js/msgType.js',
    'src/js/dwr/dwr-exception.js',
    'src/js/system-msg/bulletin.js',
    'src/js/system-msg/no_read_message.js',
    'src/js/left_nav.js'
];    

//要合并的css文件
var cssArray = [
        'src/css/chat/chatnew.css',
        'src/css/skin/physician.css',
        'src/css/reset.css',
        'src/css/style.css',
        'src/css/followup/media_chat.css',
        'src/css/xk-drop.css',
        'src/css/swiper.css',
        'src/js/lib/umeditor/themes/default/css/umeditor.css',
        'src/css/fontawesome.css',
        'src/css/featureSpace.css'
    ];


//清空目标文件夹
gulp.task('clean',function(){
    //read参数为false表示不读取文件的内容
    return gulp.src('dist/',{read:false})
        .pipe(clean());
});

//将um编辑器库拷贝到目标文件夹
gulp.task('copy_js_umeditor',function(){
    return gulp.src('src/js/lib/umeditor/**/*')
        .pipe(gulp.dest('dist/js/lib/umeditor'));
});

//将时间编辑器拷贝到目标文件夹
gulp.task('copy_js_date',function(){
    return gulp.src('src/js/date-tool/**/*')
        .pipe(gulp.dest('dist/js/date-tool'));
});



gulp.task('replace_js_login',function(){
    gulp.src('src/js/user/login.js')
        .pipe(replace('bindLoginEvent();',''))
        .pipe(gulp.dest('src/js/user'));
});



gulp.task('replace_css_um',function(){
    gulp.src('src/js/lib/umeditor/themes/default/css/umeditor.css')
        .pipe(replace('../images/','../js/lib/umeditor/themes/default/images/'))
        .pipe(gulp.dest('src/js/lib/umeditor/themes/default/css'));
});


//合并css文件
gulp.task('css_concat',['replace_css_um'],function(){
    return gulp.src(cssArray)
        .pipe(concat('xk.css'))
        .pipe(gulp.dest('src/css'))
});

//压缩css文件、为css文件添加上版本号
gulp.task('css_min_version',['css_concat'],function(){
    return gulp.src('src/css/**/*.css')
        //压缩文件
        .pipe(cssmin({
            advanced: false,
            compatibility: 'ie7',
            keepBreaks: false
        }))
        //添加上版本号
        .pipe(rev())
        .pipe(gulp.dest('dist/css'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('dist/manifest/css'));
});

//合并js文件
gulp.task('js_concat_xk',['copy_js_umeditor','copy_js_date','replace_js_login'],function(){
    return gulp.src(xk_jsArray)
        .pipe(concat('xk.js'))
        .pipe(gulp.dest('src/js'));    

});

gulp.task('js_concat_websocket',function(){
    return gulp.src(websocket_jsArray)
        .pipe(concat('websocket.js'))
        .pipe(gulp.dest('src/js'));    

});



//压缩js文件,为js文件添加上版本号
gulp.task('js_min_version',['js_concat_xk','js_concat_websocket'],function(){
    return gulp.src('src/js/**/*.js')
        //压缩文件
        .pipe(uglify())
        //添加上版本号
        .pipe(rev())
        .pipe(gulp.dest('dist/js'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('dist/manifest/js'));
});

//为图片文件添加上版本号
gulp.task('image_version',function(){
    return gulp.src('src/images/**/*.{png,jpg,gif,ico}')
        .pipe(rev())
        .pipe(gulp.dest('dist/images'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('dist/manifest/images'));
});

//html模板更改引用路径
gulp.task('html_replace',['css_min_version','js_min_version','image_version'],function(){
    return gulp.src(['dist/manifest/**/*.json','src/page/**/*.jsp'])
        .pipe(revCollector({
            replaceReved:true
        }))
        .pipe(gulp.dest('dist/page'));
});


//默认执行任务
gulp.task('default',['clean'],function(){
    gulp.start('html_replace');
});

这段时间学习收集的,感觉已经相对完善了,分享下:

var gulp = require('gulp');
var del = require('del');
var rev = require('gulp-rev');
var nano = require('gulp-cssnano');
var uglify = require('gulp-uglify')
var useref = require('gulp-useref');
var imagemin = require('gulp-imagemin');
var spriter = require('gulp-css-spriter');
var revCollector = require('gulp-rev-collector');
var browserSync = require('browser-sync').create();
var gulpSequence = require('gulp-sequence');
var uncss = require('gulp-uncss');
var htmlmin = require('gulp-htmlmin');


gulp.task('del_dist', function() {
    return del(['dist', 'tmp']);
});

/*
 * 处理HTML内部的模板标签
 */
gulp.task('useref', function() {
    return gulp.src('./src/view/*.html')
        .pipe(useref())
        .pipe(gulp.dest('./tmp/useref/view/'));
});

gulp.task('useref-img', function() {
    return gulp.src('./src/img/**/*')
        .pipe(imagemin())
        .pipe(gulp.dest('./tmp/useref/img/'));
});

gulp.task('min-css', function() {
    return gulp.src('./tmp/useref/css/*.css')
        .pipe(nano({
            discardComments: {
                removeAll: true
            }
        }))
        .pipe(gulp.dest('./tmp/useref/css/'));
});

gulp.task('sprite', function() {
    return gulp.src('./tmp/useref/css/*.css')
        .pipe(spriter({
            'spriteSheet': './tmp/useref/img/spritesheet.png',
            'pathToSpriteSheetFromCSS': '../img/spritesheet.png'
        }))
        .pipe(gulp.dest('./tmp/useref/css/'));
});


/*
 * 图片处理
 */
gulp.task('rev-img', function() {
    gulp.src('./tmp/useref/img/**/*')
        .pipe(rev())
        .pipe(gulp.dest('./tmp/rev/img/'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('./tmp/rev/img/'));
});

/*
 * css加版本号
 */
gulp.task('rev-css', function() {
    return gulp.src('./tmp/useref/css/*.css')
        .pipe(rev())
        .pipe(uncss({
            html: ['./tmp/**/*.html'],
            ignore: [/^.g-bd ul li .info/]
        })).pipe(nano({
            discardComments: {
                removeAll: true
            }
        }))
        .pipe(gulp.dest('./tmp/rev/css/'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('./tmp/rev/css/'));
});

/*
 * js加版本号
 */
gulp.task('rev-js', function() {
    return gulp.src(['./tmp/useref/js/*.js'])
        .pipe(rev())
        .pipe(uglify())
        .pipe(gulp.dest('./tmp/rev/js/'))
        .pipe(rev.manifest())
        .pipe(gulp.dest('./tmp/rev/js/'));
});

/*
 * 分析resource-map, 分配资源到HTML
 */
gulp.task('rev-collector-css', function() {
    return gulp.src(['./tmp/rev/img/*.json', './tmp/rev/css/*.css'])
        .pipe(revCollector())
        .pipe(gulp.dest('./dist/css/'));
});

gulp.task('rev-collector-html', function() {
    return gulp.src(['./tmp/rev/**/*.json', './tmp/useref/view/*.html'])
        .pipe(revCollector())
        .pipe(htmlmin({
            // collapseWhitespace: true,
            removeComments: true
        }))
        .pipe(gulp.dest('./dist/view/'));
});

gulp.task('rev-collector-img', function() {
    return gulp.src(['./tmp/rev/img/*', '!./tmp/rev/img/*.json'])
        .pipe(gulp.dest('./dist/img/'));
});

gulp.task('rev-collector-js', function() {
    return gulp.src('./tmp/rev/js/*.js')
        .pipe(gulp.dest('./dist/js/'));
});


// 静态服务器
gulp.task('bs', function() {
    browserSync.init({
        files: "**", //监听整个项目
        server: {
            baseDir: "./src/"
        }
    });
});

// 代理
gulp.task('bsp', function() {
    browserSync.init({
        proxy: "你的域名或IP"
    });
});



gulp.task('queue', gulpSequence(
    'del_dist', ['useref', 'useref-img'],
    'min-css', 'sprite', ['rev-img', 'rev-js', 'rev-css'], ['rev-collector-html'], ['rev-collector-css'], ['rev-collector-js'], ['rev-collector-img']
));

gulp.task('default', ['bs'], function() {
    del(['tmp/']);
});

赞一个!!!!!!!!!

上个月也帮项目重新调整了下gulp

  • 实现的功能

    • JsHint语法检查

    • Js代码风格检查

    • 首页资源压缩

    • 所有文件加上md5戳

    • 自动备份功能

      
      只备份当天第一次发布时的备份,也就是说备份是之前的,今天不论发布多少次不会在备份,保证备份是上个版本的可用版本; 备份文件只保留最多3个不同日期的备份。    
      
'use strict';
var gulp = require('gulp'),
  uglify = require('gulp-uglify'),
  minifyCSS = require('gulp-minify-css'),
  jshint = require('gulp-jshint'),
  jscs = require('gulp-jscs'),
  rimraf = require('rimraf'),
  minifyHTML = require('gulp-minify-html'),
  gulpCopy = require('gulp-copy'),
  usemin = require('gulp-usemin'),
  flatten = require('gulp-flatten'),
  rev = require('gulp-rev'),
  RevAll = require('gulp-rev-all'),
  filter = require('gulp-filter'),
  csso = require('gulp-csso'),
  useref = require('gulp-useref'),
  rename = require('gulp-rename'),
  fs = require('fs'),
  copyDir = require('copy-dir')
  ;

var paths = {
  // 主要 watch 使用,检测语法
  scripts: [
    'components/common/*.js',
    'components/directives/*.js',
    'components/filters/*.js',
    'components/routers/*.js',
    'components/services/*.js',
    'modules/**/*.js'
  ],
  // release 配置
  release: {
    //可以直接复制的静态文件
    staticFiles: [
      './bower_components/**/*',
      './img/**/*',
      './mobile/**'
    ],
    fonts: [
      './bower_components/font-awesome/fonts/*',
      './bower_components/bootstrap/fonts/*'
    ]
  },
  output: './prepare',
  backup: './backup'
};

gulp.task('clean', ['auto-backup'], function () {
  rimraf.sync('./prepare');
  rimraf.sync('./rev');
});
//JShint检查
gulp.task('jshint', function () {
  return gulp.src(paths.scripts)
    .pipe(jshint())
    .pipe(jshint.reporter('default'));
});

//js代码风格检查
gulp.task('jscs', function () {
  return gulp.src(paths.scripts)
    .pipe(jscs());
});

gulp.task('watch', function () {
  return gulp.watch(paths.scripts, ['jshint', 'jscs']);
});

//复制静态文件
gulp.task('copyStaticFile', ['copyFonts'], function () {
  return gulp.src(paths.release.staticFiles)
    .pipe(gulpCopy(paths.output));
});
//字体文件
gulp.task('copyFonts', function () {
  return gulp.src(paths.release.fonts)
    .pipe(flatten())
    .pipe(gulp.dest(paths.output + '/fonts'));
});

gulp.task('usemin', ['copyStaticFile', 'md5-all'], function () {
  return gulp.src(paths.output + '/*.html', {base: paths.output})
    .pipe(usemin({
      css: [rev],
      assets: [rev],
      angular: [rev],
      app: [rev]
    }))
    .pipe(gulp.dest(paths.output))
    ;
});

gulp.task('uglifyJs', ['jshint', 'usemin'], function () {
  return gulp.src([
    paths.output + '/js/*.js'
  ]).pipe(uglify({
      mangle: false
    }))
    .pipe(gulp.dest(paths.output + '/js/'));
});

//因为index.html也被md5所以需要重命名一下
gulp.task('rename-index', ['clean', 'uglifyJs'], function () {
  return gulp.src(paths.output + '/*.html')
    .pipe(rename('index.html'))
    .pipe(gulp.dest(paths.output))
    ;
});

//将所有的js, html 加上md5
gulp.task('md5-all', function () {
  var files = {
    js: [
      './components/**/*.js',
      './modules/**/*.js'
    ],
    html: [
      './components/**/*.html',
      './modules/**/*.html'
    ],
    css: [
      './css/**/*.css'
    ]
  };
  var jsFilter = filter(files.js, {restore: true}),
    htmlFilter = filter(files.html, {restore: true}),
    cssFilter = filter(files.css, {restore: true});

  var revAll = new RevAll({
    debug: !true,
    replacer: function (fragment, replaceRegExp, newReference, referencedFile) {
      //这里修正了gulp-rev-all的替换规则,目的是不替换跟文件名同名的变量
      if (newReference.indexOf('/') === -1) {
        fragment.contents = fragment.contents.replace(replaceRegExp, '$1' + '$2' + '$3$4');
      } else {
        fragment.contents = fragment.contents.replace(replaceRegExp, '$1' + newReference + '$3$4');
      }
    }
  });

  return gulp.src([
      './components/**',
      './modules/**',
      './css/**',
      'index.html'
    ])
    .pipe(htmlFilter)
    .pipe(minifyHTML())
    .pipe(useref())
    .pipe(htmlFilter.restore)

    .pipe(jsFilter)
    .pipe(uglify({
      mangle: false
    }))
    .pipe(jsFilter.restore)

    //css
    .pipe(cssFilter)
    .pipe(minifyCSS())
    .pipe(csso())
    .pipe(cssFilter.restore)
    //
    .pipe(revAll.revision())

    .pipe(gulp.dest(paths.output))

    .pipe(revAll.manifestFile())
    .pipe(gulp.dest('./rev'))
    ;
});

//自动备份build目录到backup目录
gulp.task('auto-backup', function () {
  var date = new Date(),
    dirName = date.toISOString().split('T')[0].replace(/[\D]/g, ''),
    reg = /^\d+$/g,
    build = './build';
  dirName = paths.backup + '/' + dirName;

  fs.exists(build, function (exists) {
    if (exists) {
      //备份目录是否存在
      fs.exists(dirName, function (exist) {
        if (!exist) {
          backup();
        }
      });
    }
  });
  function backup() {
    fs.readdir('./backup', function (err, data) {
      var dirs = [], l;
      if (data && data.length > 0) {
        for (var i = 0, j = data.length; i < j; i++) {
          if (data[i].match(reg)) {
            dirs.push(data[i]);
          }
        }
        if (dirs.length > 2) {
          for (i = 0, l = dirs.length; i < l - 1; i++) {
            rimraf.sync('./backup/' + dirs[i]);
          }
        }
        rimraf.sync(dirName);
      }
      copyDir.sync(build, dirName);
    });
  }
});

gulp.task('renameDir', ['rename-index'], function () {

  rimraf.sync('./build');

  // 文件拷贝
  return gulp.src('prepare/**/*')
    .pipe(gulp.dest('build'));

});

gulp.task('default', ['watch']);

gulp.task('release', ['renameDir']);
var gulp = require('gulp'), // 必须先引入gulp插件
    clean = require('gulp-clean'),  // 文件删除
    less = require('gulp-less'), // less 编译
    gutil = require('gulp-util'),// 控制台着色
    cached = require('gulp-cached'), // 缓存当前任务中的文件,只让已修改的文件通过管道
    uglify = require('gulp-uglify'), // js 压缩
    rename = require('gulp-rename'), // 重命名
    concat = require('gulp-concat'), // 合并文件
    notify = require('gulp-notify'), // 修改提醒
    cssnano = require('gulp-cssnano'), // CSS 压缩
    imagemin = require('gulp-imagemin'), // 图片优化
    browserSync = require('browser-sync'), // 保存自动刷新
    autoprefixer = require('gulp-autoprefixer');// 添加 CSS 浏览器前缀

//--------------------------common  tasks-----------------------------

//编译less--发布到本文件夹下相应目录
gulp.task('lessLocal', function() {
    return gulp.src('src/css/*.less',{base:'./src'})
    .pipe(cached('less'))
    .pipe(less())
    .pipe(autoprefixer('last 6 version'))
    .pipe(gulp.dest('src'));
});



//|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
//编译lessEclipse——方便与开发联调,发布到tomcat和eclipse相应项目目录中
gulp.task('lessEclipse', function() {
    return gulp.src('src/cssEclispe/*.less',{base:'./src'})
    .pipe(cached('less'))
    .pipe(less())
    .pipe(autoprefixer('last 6 version'))
    .pipe(gulp.dest('src'));
});

gulp.task('distCopyEclipse',function(){
    return gulp.src('src/cssEclispe/*',{nodir:true})
    .pipe(cached('distCopyEclipse'))
    .pipe(gulp.dest('D:/workSpace/makerplateform/webapp/instantcommunication/theme/css'))
    .pipe(gulp.dest('D:/tomcat7/webapps/makerplateform/instantcommunication/theme/css'));
});
//||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||





//distCopy
gulp.task('distCopy',function(){
    return gulp.src('src/**/*',{base:'./src'})
    .pipe(cached('distCopy'))
    .pipe(gulp.dest('dist'));
});

//图片压缩
gulp.task('imgmin', function() {
    return gulp.src('src/img/**/*.{jpg,jpeg,png,gif}',{base:'./src'})
    .pipe(cached('imgmin'))
    // 取值范围:0-7(优化等级),是否无损压缩jpg图片,是否隔行扫描gif进行渲染,是否多次优化svg直到完全优化
    .pipe(imagemin({optimizationLevel: 5, progressive: true, interlaced: true, multipass: true}))
    .pipe(gulp.dest('dist'));
});

//css压缩
gulp.task('cssmin', function() {
    return gulp.src(['src/**/*.css','!src/**/*.min.css','!src/lib/**/*.css'],{base:'./src'})
    .pipe(cached('cssmin'))
    .pipe(cssnano())
    .pipe(gulp.dest('dist'));
});

//jsmin
gulp.task('jsmin', function() {
    return gulp.src(['src/js/*.js','!src/js/*.min.js'],{base:'./src'})
    .pipe(cached('jsmin'))
    .pipe(uglify())
    .pipe(gulp.dest('dist'));
});

//发布任务
gulp.task('distMin', 
    gulp.series('lessLocal','distCopy',
        gulp.parallel('imgmin','cssmin','jsmin')
    )
);
gulp.task('distUnMin', 
    gulp.series('distCopy',
        gulp.parallel('imgmin')
    )
);


//---------------------- server  tasks-------------------------
//浏览器刷新    
gulp.task('default', function() {  
    browserSync.init({  
        //指定服务器启动根目录
        server: "./src"
    });  
    // gulp.watch('src/css/*.less',gulp.series('lessLocal'));
    gulp.watch('src/cssEclispe/*.less',gulp.series('lessEclipse','distCopyEclipse'));
    gulp.watch("./src/**/*.*").on('change',browserSync.reload);
});

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏