gulpfile.js 2.84 KB
/**
 * gulp file 执行compass解析,spm build以及文件合并压缩等
 * author: xuqi(qi.xu@yoho.cn)
 * date; 2015/3/27
 */
var gulp = require('gulp'),
    fs = require('fs'),
    exec = require('child_process').exec,
    concat = require('gulp-concat'),
    ftp = require('gulp-ftp'),
    uglify = require('gulp-uglify'),
    transport = require('gulp-spm'),
    Package = require('father').SpmPackage,
    md5 = require('gulp-md5');
    
var config = JSON.parse(fs.readFileSync('./package.json').toString()),
    distDir = {
        libJs: 'dist/' + config.name + '/',
        js: 'dist/' + config.name + '/' + config.version,
        css: 'dist/' + config.name + '/' + config.version,
        image: 'dist/' + config.name + '/assets/images',
        fonts: 'dist/' + config.name + '/assets/fonts'
    },
    cdnDomain = 'http://cdn.yoho.cn/',
    ftpConfig = {
        host: '218.94.75.58',
        user: 'php',
        pass: 'yoho9646'
    };

gulp.task('dist', function() {
    var ftpstream = ftp(ftpConfig);
    return gulp.src('dist/**/')
        .pipe(ftpstream)
        .pipe(gutil.noop());
});

gulp.task('build', ['libs-build']);
//库文件打包
gulp.task('libs-build', ['pre-libs', 'min-libs', 'clear-libs']);

gulp.task('pre-libs', function() {
    libPkgPre();
    var pkg = new Package(__dirname);
    return gulp.src(pkg.main)
        .pipe(transport({
            pkg: pkg
        }))
        .pipe(gulp.dest(distDir.libJs));
});

gulp.task('min-libs', ['pre-libs'], function() {
    return gulp.src(['sea/sea-debug.js', distDir.libJs + 'libs.js'])
        .pipe(concat('libs.js'))
        .pipe(uglify())
        .pipe(md5())
        .pipe(gulp.dest(distDir.libJs));
});

gulp.task('clear-libs', ['min-libs'], function() {
    fs.renameSync('package_bak.json', 'package.json'); //恢复原包配置文件
    fs.unlinkSync(distDir.libJs + 'libs.js'); //删除md5前生成的lib
    fs.unlinkSync('./libs.js'); //删除入口文件
});

//库文件的入口文件和过程文件的生成
function libPkgPre() {
    var obj = {
            name: config.name,
            version: config.version,
            spm: config.spm
        },
        libCon, libsjs = '',
        key,
        libDir = distDir.js + '';
    obj.spm.main = 'libs.js';
    obj.spm.buildArgs = '--idleading {{}} --include all';

    libCon = JSON.stringify(obj);
    fs.renameSync('package.json', 'package_bak.json');
    fs.writeFileSync('package.json', libCon); //生成库文件pkg配置
    var packages = [];
    for (key in obj.spm.dependencies) {
        if (obj.spm.inside && obj.spm.inside[key]) {
            packages.push(obj.spm.inside[key]);
        } else {
            packages.push(key);
        }
    }
    for (var i = 0; i < packages.length; i++) {
        libsjs += "require('" + packages[i] + "');";
    }

    fs.writeFileSync('libs.js', libsjs); //写入口文件
    return libDir;
}