刷新拜拜~gulp-livereload


  早就想要自動自動自動刷新了啊,曾經用grunt實現過,但是是yeoman建好的。。其中很多任務我是用不到的啊,為了干凈還是得要自己寫啊哈哈(現在我只想要自動刷新)。

  首先node是必須的了~就不說怎么裝了。

  然后先建好文件夾,安裝gulp和gulp-livereload,執行:

 cnpm install gulp gulp-livereload

  以上用了淘寶鏡像,也可以用npm安裝,只是個demo,沒有package.json,然后創建gulpfile.js,如下:

var gulp = require('gulp'),
    livereload = require('gulp-livereload');

gulp.task('watch', function() {
    livereload.listen();
    gulp.watch('app/**/*.*',function(file){
        livereload.changed(file.path);
    });
});

  大概意思是監聽app文件夾里所有文件,如果有變化就發送給livereload服務器。gulp-livereload原話如下:

Alternatively, you can call this function to send changes to the livereload server. You should provide either a simple string or an object, if an object is given it expects the object to have a path property.

  再你還要建個app文件夾,然后在里面寫個demo.html試試。隨便寫點~稍后有奇效。然后執行:

gulp watch

  在瀏覽器上訪問localhost:35729(這東西默認的端口),會看到:

{
  "tinylr": "Welcome",
  "version": "0.1.6"
}

  但其實並沒什么x用哈哈哈~~不管怎么折騰路徑還會告訴你no such route啊!

{
  "error": "not_found",
  "reason": "no such route"
}

  是!因!為!。。看github的grunt問答環節原話:

The livereload in this task only handles livereloading. It doesn't provide a static file server. You would use grunt-contrib-connect or some other method to serve files (express, restify, jaws, apache, nginx, etc).

The chrome live reload extension will create a connection through a socket to the livereload server this watch task has started on 35729. When the watch task is triggered it informs the livereload server which then through the socket will inform the chrome extension and reload the necessary portions of the page.

I agree though we need better docs explaining this as you're not the first person to get tripped up by this.

  歌詞大意是:在這個任務中livereload只處理livereloading,它不提供靜態文件服務器。。。提問鏈接

  所以還需要裝個http-server,我應該早點說的。。歐~我好壞喔,這里我全局裝啦,像這樣:

cnpm install http-server -g

  用npm是可以的。。只要不嫌慢。

  還需要個chrome插件:livereload,這個是真慢。。

  然后關掉之前的gulp watch吧,可以先進到app目錄下,其實在項目根目錄也是可以de~,執行:

http-server

  然后在項目根目錄下繼續:

gulp watch

  http-server默認端口是8080,所以可以通過訪問localhost:8080找到你要的自動刷新的那個demo文件。再確保已經安裝了liveReload插件~點開它,像這樣(右邊那個刷新里有實心圈):

  然后你就可以盡情的保存保存了~會刷新。。尊的不用F5 || cmd R了。。

 

 

  附上DEMO:github地址

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM