`

gulp build

 
阅读更多

gulp打包脚本  

var gulp = require('gulp');
var gutil = require('gulp-util');
var chalk = require('chalk');
var fs = require('fs');
var _ = require('underscore');
var path = require('path');
var amdOptimize = require("amd-optimize");
var concat = require('gulp-concat');
var rimraf = require('gulp-rimraf');
var uglify = require('gulp-uglify');
var through2 = require("through2");
var ejs = require("gulp-ejs");
var less = require('gulp-less');
var minifyCSS = require('gulp-minify-css');
var runSequence = require('run-sequence');
// var imagemin = require('gulp-imagemin');
var zip = require('gulp-zip');
var shell = require('child_process');
var pkg = require('./package.json');
var merge = require("merge-stream");
var BUILD_TIMESTAMP = gutil.date(new Date(), "yyyymmddHHMMss");
var Utils = require("./gulputil/utils");
var htmlmin = require('gulp-htmlmin');
var Config = require("./gulputil/gulp.config")();
//获取时间戳
pkg.build = BUILD_TIMESTAMP;
// 设置默认工作目录
process.chdir(Config.workDir);

// 获取管道env参数
var argv = process.argv.slice(2);
//检查环境变量参数
var env = Config.checkEnv(argv);
//设置根目录
var CONTEXT_PATH = Config.CONTEXT_PATH;
//设置环境变量
var nativeApi = Config.nativeApi;

var handleEnv = Config.handleEnv();

/*
 * 清空目标工程目录
 */
gulp.task('clean', function() {
    return gulp.src(Config.clean_src, {
            read: false
        })
        .pipe(rimraf({
            force: true
        }));
});

/*
 * 拷贝文件到目标工程目录
 */
gulp.task('copy', function() {
    return gulp.src(Config.copy_src)
        .pipe(handleEnv())
        .pipe(gulp.dest(Config.dest));
});

/*
 * 拷贝源文件文件到目标工程目录
 */
gulp.task('source', function() {
    return gulp.src(Config.source_src)
        .pipe(gulp.dest(Config.source_dest));
});
/*
 * 编译ejs页面
 */
gulp.task("ejs", function() {
    return gulp.src(Config.ejs_src)
        .pipe(ejs({
            ctx: CONTEXT_PATH,
            _build: {
                pkg: pkg,
                version: pkg.version,
                ts: BUILD_TIMESTAMP,
                env: env,
                nativeApi: nativeApi
            },
            Utils: new Utils(env),
            _: _,
            data: {},
            delimiter: "@"
        }, {
            root: __dirname + "/templates"
        }))
        .pipe(htmlmin({collapseWhitespace: true}))
        .pipe(gulp.dest(Config.ejs_dest));
})

/*
 * 编译less
 */
gulp.task('less', function() {
    return gulp.src(Config.less_src)
        .pipe(less({
            Config: [path.join(__dirname, 'less', 'includes')]
        }))
        .pipe(minifyCSS())
        .pipe(gulp.dest(Config.less_dest));
});

/*
 * 编译压缩css
 */
gulp.task('minifycss', function() {
    return gulp.src(Config.minifycss_src)
        .pipe(minifyCSS())
        .pipe(gulp.dest(Config.minifycss_dest));
});

// /*
// * 图片压缩
// */
// gulp.task("imagemin",function(){
//  return gulp.src(Config.src+'/images/*')
//         .pipe(imagemin({
//             progressive: true,
//             optimizationLevel:3,
//             svgoPlugins: [{removeViewBox: false}]
//         }))
//         .pipe(gulp.dest(Config.dest+'/images'));
// })

/*
 * 编译压缩js
 */
gulp.task('uglifyjs', function() {
    return gulp.src(Config.uglifyjs_src)
        .pipe(handleEnv())
        .pipe(uglify({
            // output: {
                // max_line_len: 120
            // }
        }).on("error", gutil.log))
        .pipe(gulp.dest(Config.uglifyjs_dest));
});
// /*
//  * 编译压缩js
//  */
// gulp.task('concat_modules', function() {
//     var files = fs.readdirSync(Config.concat_modules_src);
//     var dirs = [];
//     var sequence = [];
//     _.each(files, function(fn) {
//         var fname = Config.concat_modules_src + "/"+fn;
//         var stat = fs.lstatSync(fname);
//         if (stat.isDirectory() == true) {
//             dirs.push(fname)
//         }
//         sequence.push(
//             gulp.src(fname+"/**/*.js")
//             .pipe(concat("main.js"))
//             .pipe(gulp.dest(Config.concat_modules_dest+"/"+fn))
//         )
//     })
//     return merge.apply(this,sequence);
//     // return gulp.src(Config.uglifyjs_src)
//     //     .pipe(concat({
//     //         output: {
//     //             max_line_len: 120
//     //         }
//     //     }).on("error", gutil.log))
//     //     .pipe(gulp.dest(Config.uglifyjs_dest));
// });

/*
 * require js 优化
 */
gulp.task("js_optimize", function() {
    var sequence = [];
    sequence.push(
        // 优化common
        gulp.src(Config.src + "/js/**/*.js")
        .pipe(amdOptimize("C", {
            configFile: Config.src + "/lib/require-config.js",
            paths: Config.exclude
        }))
        .pipe(handleEnv())
        // 合并
        .pipe(concat("common.js"))
        // .pipe(uglify().on("error", gutil.log))
        // 输出
        .pipe(gulp.dest(Config.dest + "/js/common"))
    );


    var files = fs.readdirSync(Config.concat_modules_src);
    var dirs = [];
    var sequence = [];
    _.each(files, function(fn) {
        var fname = Config.concat_modules_src + "/" + fn;
        var stat = fs.lstatSync(fname);
        if (stat.isDirectory() == true) {
            if (fs.existsSync(Config.src + "/modules/" + fn + "/index.js")) {
                sequence.push(
                    // 优化common
                    gulp.src(Config.src + "/modules/**/*.js")
                    .pipe(amdOptimize("modules/" + fn + "/index", {
                        configFile: Config.src + "/lib/require-config.js",
                        paths: Config.exclude
                    }))
                    .pipe(handleEnv())
                    // 合并
                    .pipe(concat("index.js"))
                    // .pipe(uglify().on("error", gutil.log))
                    // 输出
                    .pipe(gulp.dest(Config.concat_modules_dest + "/" + fn))
                )

            }
        }
    })
    return merge.apply(this, sequence);
});

/*
 * 打包zip
 */
gulp.task('archive', function() {
    return gulp.src(Config.archive_src)
        .pipe(zip(pkg.name + "_v_" + pkg.version.replace(/\./g, "_") + "_" + env.toLowerCase() + "_" + BUILD_TIMESTAMP + '.zip'))
        .pipe(gulp.dest(Config.output));
});

// gulp.task('archive', function () {
//     return gulp.src('src/*')
//         .pipe(zip('archive.zip'))
//         .pipe(gulp.dest('dist'));
// });




/*
 * 部署到测试环境
 */
gulp.task('deploy', function() {
});

gulp.task('clean_patch', function() {
  return gulp.src(Config.clean_patch, { read: false })
    .pipe(rimraf({ force: true }));
});

/*
* 拷贝文件到目标工程目录
*/
gulp.task('copy_patch', function() {
    var filelist = fs.readFileSync("../patchlist.txt","UTF-8");
    filelist = filelist.replace(/\r/g,"");
    var list = filelist.split("\n");
    var rs = [];
    var obj = {};
    _.each(list,function(item){
        if(/^modules/.test(item)){
            var items = item.split("/");
            item = [items[0],items[1],"**/*"].join("/");
        }
        obj[item]=true;
    })
    for(var key in obj){
        console.log(key);
        rs.push(key);
    }
    rs.push("js/version.js");
    return gulp.src(rs,{cwd:Config.dest,base:Config.dest})
        .pipe(gulp.dest(Config.patch));
});


/*
* 开始构建
*/
gulp.task('patch', function (callback) {
      runSequence(
        "clean_patch",
        "copy_patch",
        function (error) {
          if (error) {
            console.log(error.message);
          } else {
            console.log('RELEASE FINISHED SUCCESSFULLY');
          }
          callback(error);
     });
});

/*
 * 清空output目录
 */
gulp.task('clean_output', function() {
    return gulp.src(Config.output, {
            read: false
        })
        .pipe(rimraf({
            force: true
        }));
});

/*
 * 把dist拷贝到output目录下
 */
gulp.task('copy_output', function() {
    return gulp.src(Config.dest+"/**/*",{cwd:Config.dest,base:Config.dest})
        .pipe(gulp.dest(Config.output+"/"+env.toLowerCase()));
});

/*
 * 打包zip
 */
gulp.task('archive_output', function() {
    return gulp.src(Config.output+"/**/*")
        .pipe(zip('output.zip'))
        .pipe(gulp.dest(Config.output));
});

/*
 * 开始构建
 */
gulp.task('build', function(callback) {
    runSequence(
        "clean",
        'less',
        "copy",
        'ejs',
        'source',
        'js_optimize',//这个运行时需要10几分钟,暂时注释掉
        'uglifyjs',
        // 'minifycss',
        // 'archive',
        function(error) {
            if (error) {
                console.log(error.message);
            } else {
                console.log('RELEASE FINISHED SUCCESSFULLY');
            }
            callback(error);
        });
});



/*
 *   监听less
*/ 
gulp.task('watchless', function() {
    return gulp.watch(Config.src + "/less/**/*.less",function(event){
        console.log(event.path);
        gulp.start(["less"]);
    });
});

/*
 *   监听js
*/
gulp.task("watchjs",function(){
    return gulp.watch(Config.src + "/**/*.js",function(event){
        console.log(event.path);
        gulp.start(["js_optimize","uglifyjs"]);
    });
});

/*
 *   监听ejs
*/
gulp.task("watchejs",function(){
    return gulp.watch(Config.templates + "/**/*.ejs",function(event){
        console.log(event.path);
        gulp.start(["ejs"]);
    });
});
/*
* watch监听 js javascript ejs
*/
gulp.task('watch', function (callback){
    runSequence(
        "watchless",
        "watchjs",
        "watchejs",
        function(error) {
            if (error) {
                console.log(error.message);
            } else {
                console.log('RELEASE FINISHED SUCCESSFULLY');
            }
            callback(error);
        });
});
/*
* 编译build,然后watch
*/
gulp.task('default', function (callback){
    runSequence(
        "build",
        "watch",
        function(error) {
            if (error) {
                console.log(error.message);
            } else {
                console.log('RELEASE FINISHED SUCCESSFULLY');
            }
            callback(error);
        });
});



 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics