使用Gulp構建Web服務器

問題 
  • 1. 在寫前端界面代碼時,想調試的時候須要配置一個Apache或者Nginx服務器
  • 2. 每次修改代碼都須要刷新一下,驗證效果。

解決方案 

Gulp + Gulp-connect +watch + livereload 

Gulp是目前風頭正勁的前端自動化工具,有取代Grunt的趨勢。初次使用,一下就被其簡潔的語法折服了,目前我仍是隻是在小項目中使用,通常語法簡潔的工具在面對大型,複雜項目時都會有不足,這點留待之後考察了。 

Gulp是基於NodeJS的,所以使用以前須要先安裝NodeJS, 不得不說NodeJs繁榮了整個前端開發生態啊。有了NodeJS以後,安裝Gulp就很容易了。 

Shell代碼  
  1. npm install -g gulp  


有了Gulp以後,主角登場,安裝Gulp插件gulp-connect,Gulp的插件機制很是好,每一個插件的功能都很單一,純粹。gulp-connect的功能就是在本地啓動一個Web Server 

Shell代碼  
  1. npm install -g gulp-connect  


安裝完了插件以後,就能夠寫Gulp構建腳本了,Gulp的腳本很是簡單,就是一個Javascript腳本定義的DSL,下面就是一個經過gulp-connect定義一個本地Server服務,而後經過watch任務和livereload設置實現自動刷新的: 
Javascript代碼  
//引入插件
var gulp = require('gulp');
var connect = require('gulp-connect');

//建立watch任務去檢測html文件,其定義了當html改動以後,去調用一個Gulp的Task
gulp.task('watch', function () {
    gulp.watch(['./www/*.html'], ['html']);
});

//使用connect啓動一個Web服務器
gulp.task('connect', function () {
    connect.server({
        root: 'www',
        livereload: true
    });
});

gulp.task('html', function () {
    gulp.src('./www/*.html')
        .pipe(connect.reload());
});

//運行Gulp時,默認的Task
gulp.task('default', ['connect', 'watch']);

 



經過在項目目錄下,運行命令‘gulp’: 
Shell代碼  
[gulp] Using gulpfile ~/Documents/workspace/ionic_workspace/open_party/gulpfile.js
[gulp] Starting 'connect'...
[gulp] Server started http://localhost:8080
[gulp] LiveReload started on port 35729
[gulp] Finished 'connect' after 13 ms
[gulp] Starting 'watch'...
[gulp] Finished 'watch' after 6.69 ms
[gulp] Starting 'default'...
[gulp] Finished 'default' after 11 μs

 


而後在修改代碼時,界面自動刷新,效果以下: 

 

原文:http://ningandjiao.iteye.com/blog/2070572?utm_source=tuicool&utm_medium=referral
相關文章
相關標籤/搜索