2016年3月14日 星期一

gulp 前端最佳化js和css工具

安裝gulp-cli套件
$ npm install gulp-cli -g


安裝gulp套件
$ npm install gulp --save-dev


安裝gulp plugin套件
$ npm install gulp-concat
$ npm install gulp-cssmin
$ npm install gulp-uglify
$ npm install rimraf

新增gulpfile.js
/// <binding BeforeBuild='min' Clean='clean' />
"use strict";

var gulp = require("gulp"),
    rimraf = require("rimraf"),
    concat = require("gulp-concat"),
    cssmin = require("gulp-cssmin"),
    uglify = require("gulp-uglify");

var paths = {
    webroot: "./wwwroot/"
};

paths.js = paths.webroot + "js/**/*.js";
paths.minJs = paths.webroot + "js/**/*.min.js";
paths.css = paths.webroot + "css/**/*.css";
paths.minCss = paths.webroot + "css/**/*.min.css";
paths.concatJsDest = paths.webroot + "assets/site.min.js";
paths.concatCssDest = paths.webroot + "assets/site.min.css";

gulp.task("clean:js", function (cb) {
    rimraf(paths.concatJsDest, cb);
});

gulp.task("clean:css", function (cb) {
    rimraf(paths.concatCssDest, cb);
});

gulp.task("clean", ["clean:js", "clean:css"]);

gulp.task("min:js", function () {
    return gulp.src([paths.js, "!" + paths.minJs], { base: "." })
        .pipe(concat(paths.concatJsDest))
        .pipe(uglify())
        .pipe(gulp.dest("."));
});

gulp.task("min:css", function () {
    return gulp.src([paths.css, "!" + paths.minCss])
        .pipe(concat(paths.concatCssDest))
        .pipe(cssmin())
        .pipe(gulp.dest("."));
});

gulp.task("min", ["min:js", "min:css"]);
gulp.task("default", function () {
    gulp.watch(paths.js, function () {
        gulp.run("min:js");
    });
    gulp.watch(paths.css, function () {
        gulp.run("min:css");
    });
});


執行工作
$ gulp clean
$ gulp min