gulp最佳實踐(包含js,css,html預編譯,合併,壓縮,瀏覽器自動刷新)

gulp是基於流的自動化構建工具
官方網址:http://www.gulpjs.com.cn/css

安裝須要的模塊

  1. 新建package.json,輸入下面的內容webpack

  2. 命令npm installweb

{
  "name": "autopractice",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "browser-sync": "^2.10.1",
    "coffee-script": "^1.10.0",
    "gulp": "^3.9.0",
    "gulp-clean": "^0.3.1",
    "gulp-coffee": "^2.3.1",
    "gulp-concat": "^2.6.0",
    "gulp-connect": "^2.3.1",
    "gulp-jade": "^1.1.0",
    "gulp-jshint": "^2.0.0",
    "gulp-less": "^3.0.5",
    "gulp-livereload": "^3.8.1",
    "gulp-minify-css": "^1.2.2",
    "gulp-plumber": "^1.0.1",
    "gulp-uglify": "^1.5.1",
    "gulp-webpack": "^1.5.0",
    "jade": "^1.11.0",
    "jshint": "^2.8.0"
  }
}

配置gulp

代碼說明看解釋,若是有任何疑問請查看官方入門手冊,網址在上面npm

// 導入須要的模塊
var gulp = require('gulp'),
    less = require('gulp-less'),
    jade = require('gulp-jade'),
    coffee = require('gulp-coffee'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    browserSync = require('browser-sync').create(),
    plumber = require('gulp-plumber'),
    minifyCss = require('gulp-minify-css');


// 編譯less,其中plumber是防止出錯崩潰的插件
gulp.task('less', function() {
    gulp.src('src/less/*.less')
        .pipe(plumber())
        .pipe(less())
        .pipe(gulp.dest('dist/css'));
});

// 編譯jade
gulp.task('jade', function() {
    gulp.src('src/jade/*.jade')
        .pipe(plumber())
        .pipe(jade())
        .pipe(gulp.dest('public'));
});

// 編譯coffee
gulp.task('coffee', function() {
    gulp.src('src/coffee/*.coffee')
        .pipe(plumber())
        .pipe(coffee())
        .pipe(gulp.dest('dist/js'));
});



// 將全部css文件鏈接爲一個文件並壓縮,存到public/css
gulp.task('concatCss', function() {
    gulp.src(['dist/css/*.css'])
        .pipe(concat('main.css'))
        .pipe(minifyCss())
        .pipe(gulp.dest('public/css'));
});


// 將全部js文件鏈接爲一個文件並壓縮,存到public/js
gulp.task('concatJs', function() {
    gulp.src(['dist/js/*.js'])
        .pipe(concat('main.js'))
        .pipe(uglify())
        .pipe(gulp.dest('public/js'));
});



// 默認任務
gulp.task('default', ['watch']);


// 監放任務
gulp.task('watch', function() {

    // 創建瀏覽器自動刷新服務器
    browserSync.init({
        server: {
            baseDir: "public"
        }
    });


    // 預處理
    gulp.watch('src/jade/**', ['jade']);
    gulp.watch('src/coffee/**', ['coffee']);
    gulp.watch('src/less/**', ['less']);


    // 合併壓縮
    gulp.watch('dist/css/*.css', ['concatCss']);
    gulp.watch('dist/js/*.js', ['concatJs']);


    // 自動刷新
    gulp.watch('public/**', function() {
        browserSync.reload();
    });

});

測試

控制檯運行gulp
瀏覽器將自動打開
修改任意文件,瀏覽器自動刷新
動態圖片,節約流量,xjson

相關文章
相關標籤/搜索