gulp-webserver是開啟服務器,通常和gulp-livereload結合使用。而這兩個結合使用效果,幾乎類似browser-Sync。下面是gulp-webserver和gulp-livereload的一個小demo。
源代碼下載(寄放在碼雲上)。
1. 所用的gulp-task的包及其他npm包

2.所需的目錄結構

3.gulpfile.js 中設置源碼目錄和開發目錄
var app = {
srcPath: 'src/',
devPath: 'build/'
};
4.安裝gulp-load-plugins,這個task是來避免重復require(引用模塊),所以在gulpfile.js中看到如下代碼:
var gulp = require('gulp'),
$ = require('gulp-load-plugins')();
引入gulp-load-plugins之后,使用其他模塊方法,只需要在其方法前加上“$.”,以sass為例:
gulp.task('sass',function(){
gulp.src(app.srcPath+'styles/*.scss')
.pipe($.sourcemaps.init())
.pipe($.sass())
//這里加了./ 表示生成的.map文件
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest(app.devPath + 'css'))
//單獨使用livereload監聽
//.pipe($.livereload());
});
5.設置服務器端口,和瀏覽器同步
gulp.task('webserver', function() {
gulp.src(app.devPath) // 服務器目錄(./代表根目錄)
.pipe($.webserver({ // 運行gulp-webserver
livereload: true, // 啟用LiveReload,去掉f5刷新的痛點
open: true, // 服務器啟動時自動打開網頁
port: 3000
}));
});
6. 整合默認一個任務
// 監聽任務
gulp.task('watch',function(){
gulp.watch(app.srcPath + 'styles/*.scss', ['sass']);
gulp.watch(app.srcPath + '**/*.html', ['html']) // 監聽根目錄下所有.html文件
});
//默認任務
gulp.task('default',['webserver','watch']);
發現兩個問題:
1.運行gulp,發現sass能監聽,但檢查語法錯誤能力不夠全,如下:

sass語法中變量聲明在變量調用之前,而本demo並沒因此終止監聽或者出現錯誤。
2.另外如出現錯誤,命令端口會掛掉,可以用gulp處理錯誤的task,如:gulp-plumber(傳送門)
