36
35

More than 5 years have passed since last update.

gulp.js その2 gulpでWebサーバー/ライブリロード

Last updated at Posted at 2014-06-14

※ ここで紹介している"gulp-connect"プラグインは deprecateされた。
後継の"gulp-webserver"プラグインを使うこと(» gulp-webserverプラグインの解説

"gulp-connect"プラグインを使えば、簡単に開発用Webサーバーを立ち上げ、ライブリロードで確認しながら作業することができる

準備

gulpがインストールされていることが前提

gulp-connectのインストール

npmで開発用としてインストールする
npm install --save-dev gulp-connect

gulpfile.jsの編集

gulp-connect - npm のサンプルそのまんま
事前に'app'ディレクトリを作成し、中に'index.html'と'about.html'を入れておく

【ディレクトリ構成】
テスト用ディレクトリ
 ├ gulpfile.js
 ├ app
 │ ├ index.html
 │ └ about.html
 └ node_modules

gulpfile.js
var gulp = require('gulp'),
  connect = require('gulp-connect');

//Webサーバー
gulp.task('connect', function() {
  connect.server({
    root: 'app',//ルートディレクトリ
    livereload: true //ライブリロード
  });
});

//'html'に、htmlファイルをリロードする処理を登録
gulp.task('html', function () {
  gulp.src('./app/*.html')
    .pipe(connect.reload());
});

//監視:HTMLファイルが変更されたら'html'を実行
gulp.task('watch', function () {
  gulp.watch(['./app/*.html'], ['html']);
});

//デフォルトタスクに登録
gulp.task('default', ['connect', 'watch']);


実行

ターミナルでgulp実行。
gulp

「アプリケーション"node"へのネットワーク受信接続を許可しますか?」とアラートが出るので、許可。
標準出力で、サーバーとライブリロードが開始されたことが確認できる
ホストやポート番号は connect.server() のオプションで変更できる

[09:19:18] Server started http://localhost:8080
[09:19:18] LiveReload started on port 35729

【結果】
ブラウザで http://localhost:8080 にアクセスすると、index.html が表示される
http://localhost:8080/about.html にアクセスすると、about.html が表示される
存在しないファイルにアクセスしようとすると"Cannot GET /ファイル名"と表示

ブラウザを開きながらエディタでHTMLを変更保存すると、ライブリロードが機能していることが確認できる。

参考サイト

36
35
1

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
36
35