LoginSignup
5
9

More than 5 years have passed since last update.

browser-syncを使う

Last updated at Posted at 2018-04-12

導入手順

  • npmでbrowser-syncをインストール
  • browser-syncのコンフィグ設定

事前に準備していた環境

  • Mac
  • node.jsはnodebrewでインストール済み

導入

プロジェクトディレクトリに移動して

$ cd プロジェクトディレクトリ

npmでbrowser-syncを開発用でローカルインストール。 *npmを初期化していない場合は先に初期

$ npm install browser-sync --save-dev

インストールが終わってからbrowser-syncのコンフィグファイルを生成

$ npx browser-sync init

bs-config.jsが作られる

bs-config.js
/*
 |--------------------------------------------------------------------------
 | Browser-sync config file
 |--------------------------------------------------------------------------
 |
 | For up-to-date information about the options:
 |   http://www.browsersync.io/docs/options/
 |
 | There are more options than you see here, these are just the ones that are
 | set internally. See the website for more info.
 |
 |
 */
module.exports = {
    "ui": {
        "port": 3001
    },
    "files": false,
    "watchEvents": [
        "change"
    ],
    //~~~以下続く~~~
}

設定が大量に記述されたbs-config.jsが作られるので必要な設定のみ残してあとは削除。
今回は監視ファイルとプロキシの設定だけしたかったので以下のように書き換え

bs-config.js
/*
 |--------------------------------------------------------------------------
 | Browser-sync config file
 |--------------------------------------------------------------------------
 |
 | For up-to-date information about the options:
 |   http://www.browsersync.io/docs/options/
 |
 | There are more options than you see here, these are just the ones that are
 | set internally. See the website for more info.
 |
 |
 */
module.exports = {
    "files": ["**/index.php", "css/*.css","js/**/*.js"], //phpファイルはindex.phpのみ、cssファイルとjsファイルは全て監視する
    "proxy": 'localhost:80', //ローカルホストのポートを指定、Vagrant環境などドメインやIPを指定する場合は'192.168.11.1:80'、'test.domain.com:80'などで指定する
};

最後にpackage.jsonにbrowser-syncを起動するコマンドを追加

package.json
{
    "scripts": {
        "bs": "browser-sync start --config bs-config.js"
    }
}

これで設定完了!

$ npm run bs

npmでbrowser-syncを起動すれば監視ファイルを更新するたびにブラウザが再読み込みしてくれます。

参考
rowsersyncを利用してお手軽ブラウザ確認環境をつくろう - メドピア開発者ブログ [http://tech.medpeer.co.jp/entry/2015/06/09/071758]

5
9
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
5
9