gulp-watchify で browserify と parcelify を差分ビルド

Posted: , Modified:   gulp browserify parcelify watchify JavaScript Qiita

本稿は Qiita 投稿記事 のバックアップです.

概要

English

利用するライブラリが増えてビルドに時間がかかるようになったので, watchify を使った差分ビルドを試してみる. タスクランナーに gulp を使用しているので, gulp-watchify を使い, browserifyParcelifyによるビルドを差分ビルドにする.

gulp-watchify の使い方

サンプルファイル によると,単純な使い方は,

gulp = require "gulp"
$ = require("gulp-load-plugins")()
watching = false

gulp.task "browserify", $.watchify (watchify) ->
  gulp.src "src/*.js"
    .pipe watchify
      watch:watching
    .pipe gulp.dest "public/js/"

gulp.task "watch", ->
  watching = true

となるようだ.これで,gulp browserify とすれば通常のビルドを gulp watch browserify とすれば,watchify による監視を始めることができる.

なお,gulp-load-plugins に関しては,[gulp] 効率的にプラグインを読み込む を参照.上の例では変わらないが,require を減らすために使っている.

注意

gulp-watchify をインストールしただけでは,watchify はインストールされない模様.なので,

$ npm i —save-dev watchify gulp-watchify

と両方インストールするのを忘れずに.

parcelify の利用

先ほどの例では,gulp-watchify の内部で browserify を呼んでいるため,parcelify を使う場所がない.gulp-watchify は,オプションで bundle の前に実行するコールバックを渡せるので,そこで parcelify を使う.

gulp = require "gulp"
parcelify = require "parcelify"
$ = require("gulp-load-plugins")()
watching = false

gulp.task "browserify", $.watchify (watchify) ->
  gulp.src "src/main.js"
    .pipe watchify
      extensions: [".js"]
      watch: watching
      setup: (bundle) ->
        parcelify bundle,
          bundles:
            style: "public/css/bundle.css"
    .pipe $.rename "bundle.js"
    .pipe gulp.dest "public/js/"

gulp.task "watch", ->
  watching = true

これで先ほどと同様に,gulp browserify とすれば通常のビルドを gulp watch browserify とすれば,watchify による監視を始めることができる.

上は,main.js をエントリーにスクリプトとして,出力を bundle.js にする例となっている.名前変更のために別途 gulp-rename が必要.

watchify のオプションには,browserify に渡すオプションと同じものを使える.上の例では,extensions を渡している.

参考