LoginSignup
39
40

More than 5 years have passed since last update.

gulpでブラウザのリロードを自動化してみた

Posted at

HTMLやJavaScriptを書くときにいちいちブラウザをリロードするのが面倒なので初めてgulpを使ってみたときのメモ。

参考

以下を参考に実施させていただきました。

gulp:ブラウザのリロード自動化

環境

  • Node->v4.2.2
  • npm->2.14.7

まだ、Nodeをインストールしていない場合には、インストールが必要

グローバル環境へgulpのインストール

グローバルな環境へgulpをインストールします。

$npm install -g gulp

テスト環境の作成

テスト用htmlやフォルダなどを作成します。

# テストする環境のベースとなるフォルダ
$mkdir gulp-test

# ディレクトリ移動
$cd gulp-test

# html配置用フォルダ
$mkdir src

# html作成
$vi src/index.html

テスト用にブラウザを起動したらconsole.logに文字列を出力するものを作成しました。

index.html
<html>
  <head>
    <title>test</title>
    <script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
    <script>
      $(function() {
        console.log('start init');
      });
    </script>
  </head>
  <body>
    hello
  </body>
</html>

package.jsonの作成

次の項でnpmのモジュールを追加でインストールするのですが、他の人が利用する場合にどのモジュールをインストールしたか判断できません。nodeではpackage.jsonというファイルを作成し、依存するライブラリを記述することでnpm installとすると自動で依存するモジュールをインストールすることができます。

package.jsonの雛形はnpm initで作成できるのでこれを利用します。すべてyesで大丈夫です。

$npm init
# 質問には全てyesで回答

$cat package.json
{
  "name": "gulp-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

モジュールのインストール

ブラウザ自動リロードに必要なモジュールをインストールします。--save-devオプションによってでpackage.jsonに依存しているライブラリを追記します。

$npm install --save-dev gulp
$npm install --save-dev browser-sync 

browser-syncではCのビルド?なども走るようでmakeなどが必要なようです。ubuntuであればbuild-essentialパッケージなどが必要なので適宜インストールしておいてください。

インストール時にエラーがなければOKです。
package.jsonにも追記されています

$cat package.json
{
  "name": "gulp-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "browser-sync": "^2.11.1",
    "gulp": "^3.9.1"
  }
}

gulpfile.js の作成

これは参考リンクのままです。
どのファイルを監視し、変更があった場合にリロードを実行せよというタスクとなります。

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

gulp.task('browser-sync', function() {
    browserSync.init({
        server: {
            baseDir: "src",
            index: "index.html"
        }
    });
});

gulp.task('bs-reload', function () {
    browserSync.reload();
});

// src 配下の *.html, *.css ファイルが変更されたリロード。
gulp.task('default', ['browser-sync'], function () {
    gulp.watch("src/*.html", ['bs-reload']);
    gulp.watch("src/*.css", ['bs-reload']);
});

やってみる

gulpを実行してみます。

$gulp
[07:46:55] Using gulpfile ~/gulp-test/gulpfile.js
[07:46:55] Starting 'browser-sync'...
[07:46:55] Finished 'browser-sync' after 12 ms
[07:46:55] Starting 'default'...
[07:46:55] Finished 'default' after 13 ms
[BS] Access URLs:
 -------------------------------------
       Local: http://localhost:3002
    External: http://192.168.11.2:3002
 -------------------------------------
          UI: http://localhost:3003
 UI External: http://192.168.11.2:3003
 -------------------------------------
[BS] Serving files from: src
[07:47:41] Starting 'bs-reload'...
[BS] Reloading Browsers...
[07:47:41] Finished 'bs-reload' after 2.41 ms

デフォルトのブラウザが起動され、index.htmlの内容が表示されます。

この状態でsrc/index.htmlを編集し、保存すると保存されたタイミングでブラウザが自動でリロードされ、内容の確認やconsole.logなどの確認ができるようになります。

39
40
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
39
40