LoginSignup
15
19

More than 5 years have passed since last update.

gulpでbrowserifyを使う

Posted at

gulpbrowserifyを使って、Web開発で使用するモジュールを管理します。ただ同じことはwebpackでもできるので、自分はほとんどwebpackを使っています。

browserify

以前はgulp-browserifyを使っていたんだけれども、BlackListに含まれていて推奨されない方法とされているので、直接browserifyを使います。

gulpのレシピにあるBrowserify + Uglify2 with sourcemapsあたりが参考になりそうです。

インストール

npm init
npm install gulp bower debowerify browserify vinyl-transform --save-dev

ウェブ用のパッケージはbowerでしか管理されていないこともあるので一応いれておきました。debowerifyはbowerで取得したファイルを簡略な指定によってbrowserifyで使うためのものでpackage.jsonに以下を追記する必要があります。

"browserify": {
  "transform": [
    "debowerify"
  ]
},

bowerのファイルがプロジェクトのルート直下から変更したい場合には、.bowerrcを作成してディレクトリの指定をします。

{
  "directory": "/app/bower_components"
}

gulpfile.js

var gulp = require('gulp');
var transform = require('vinyl-transform');
var browserify = require('browserify');

gulp.task('js', function() {
  return gulp.src('app/scripts/main.js')
    .pipe(transform(function(filename) {
      return browserify(filename, {
        debug: true
      }).bundle();
    }))
    .pipe(gulp.dest('dist'));
});

vinyl-transformbundleの返すファイルストリームをnpmで使用されているvinylに変換するために使われています。

watchify

browserifyでwatchしていると、ファイルの増加によってその処理時間もどんどん増えてくのでwatchのときにはWatchifyで差分コンパイルをします。

上記のサイトを参考にしました。

インストール

browserifyがインストール済みであることを想定しています。

npm install watchify vinyl-source-stream gulp-util --save

gulp-utilは必須ではないんだけど、出力されるログは色がついていたほうがわかりやすいので使いました。

gulpfile.js

var gulp = require('gulp');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var watchify   = require('watchify');
var $ = require('gulp-load-plugins')();

gulp.task('browserify', function() {
  return compile(false);
});

gulp.task('watchify', function() {
  return compile(true);
});

function compile(watch) {
  var bundler = null;
  var option = {
    debug: true
  };

  if (watch) {
    option.cache = {};
    option.packageCache = {};
    option.fullPaths = true;
    bundler = watchify(browserify(path.js, option));
  } else {
    bundler = browserify(path.js, option);
  }

  function bundle() {
    return bundler
      .bundle()
      .on('error', $.util.log.bind($.util, 'Browserify Error'))
      .pipe(source('main.js'))
      .pipe(gulp.dest(path.dist));
  }

  bundler.on('update', bundle);
  bundler.on('log', function(msg) {
    $.util.log('Finished', '\'' + $.util.colors.cyan('watchify') + '\'', msg);
  });

  return bundle();
}

// watchifyは監視しなくていい
gulp.task('watch:js', ['watchify']);

参照文献

15
19
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
15
19