LoginSignup
0
3

More than 5 years have passed since last update.

Gulpでライブリロード(Vagrant環境)

Posted at

背景

  • html, css, js等を編集した後リロードボタンを押すのがとてもつらい
  • ソース結合やらで既にgulpを導入していたのでそのまま流用したい
  • ひとりでにブラウザがリロードされるのをドヤ顔で眺めていたい

環境

  • Vagrant上のVMでApacheが動作中
  • VM上のサーバにhttp://192.168.10.10/でアクセスできる
  • ローカルの/User/ats05/Vagrant/projectをVMとの共有ディレクトリとして使用中

材料

  • npm
  • gulp
  • browser-sync

やったこと

npm、gulpは既に導入されている前提でいきます。

browser-syncのインストール

$ npm install --save-dev browser-sync 

(色々出る)

+ browser-sync@2.18.13
added 277 packages in 22.626s

確認してみましょう

$ npm ls --depth=0
myProject@1.0.0 /site/myProject
...
├──
├── browser-sync@2.18.13
├──
...

おk。
ちなみに--depth=0をつけないと依存パッケージがわらわら出てきます。注意。

gulpfile.jsにタスクを作る

ここで実現するライブリロードは

gulpのwebサーバを起動 -> 変更を検知 -> ブラウザを再読み込み

という流れ。

  • gulpのwebサーバを起動 : bs-init
  • gulp.watchで監視
  • ブラウザを再読み込み : bs-reload

こんな感じで作成します。

gulpfile.js
var gulp = require('gulp');
var bs = require('browser-sync').create();

//webサーバ起動
gulp.task('bs-init', function(){
    bs.init({
        proxy: "192.168.10.10" //ローカルサーバへのプロキシ設定
    })
})

//リロード
gulp.task('bs-reload', function(){
    bs.reload();
})

//監視タスク
gulp.task('w', ['bs-init'], function () {
    gulp.watch('/User/ats05/Vagrant/project/*', ['bs-reload']);
});

gulp.task('w', ['bs-init'], function () {
この部分ですが、gulpのタスクを作成する際には第二引数で「そのタスクの前に実行するタスク」を登録できます。
この場合にgulp.watchで監視を行うタスクを呼ぶと、監視を始める前にwebサーバの起動をしてくれるわけですね。

動かす

$ gulp w

以上。


browser-syncで起動したwebサーバがあればライブリロード自体は実現できるのですが、その場合はバックエンドを動かすことができないようです。
プロキシを通せばその辺りの検証もできます。

手元で動かしているものにはJSのconcatやhtmlの生成などを追加しています。
gulpはgruntに比べ設定ファイルが書きやすいですね。

    ...
    gulp.watch('/User/ats05/Vagrant/project/src/js/*', ['js']);
    gulp.watch('/User/ats05/Vagrant/project/src/css/*', ['sass']);
    gulp.watch('/User/ats05/Vagrant/project/src/views/*', ['ejs']);
    gulp.watch('/User/ats05/Vagrant/project/*', ['bs-reload']);
    ...

おしまい。

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3