LoginSignup
7
7

More than 5 years have passed since last update.

gulp & Browserifyでnode_modules以外のmoduleもrequireする

Last updated at Posted at 2015-05-05

サンプルプロジェクトはこちらです。

概要

このプロジェクトは、gulp & Browserify構成でnode_modules以外のmoduleもrequireする為のサンプルプロジェクトです。
以下のmoduleを、複数のパッケージ管理、パッケージ管理外からrequireしています。

app.coffee
$ = require('jquery')        # 野良からrequireしたい
_ = require('underscore')    # Bower配下からrequireしたい
Enumerable = require('linq') # node_modules配下からrequireしたい

Usage

npm install
bower install
gulp (build | watch | clean)

node_modules以外のrequire対応方法

node_modules以外のrequire対応は、flexi-requireを利用しています。

これをbrowserify.pluginに設定値とともに渡してbundleする事により、node_modules以外のmoduleもrequire出来るようにしています。

例えば、このサンプルプロジェクトではunderscore以外のmoduleをpublic/common-bundle.jsへ、アプリロジックとunderscore moduleをpublic/bundle.jsへと分けていますが、その時の処理は以下のようになっています。

gulpfile.coffee

entries = ['./lib/scripts/app.js']

# underscore以外のmoduleをcommon-bundle.jsへ
b = browserify()
b.plugin('flexi-require', {
  getFiles: () -> entries, # このファイルで使用しているmodule一覧がrequireされる
  require:['*', './non_package_modules/jquery-2.1.3.js:jquery']
  external: ['underscore']
})
b.bundle()
  .pipe(source 'common-bundle.js')
  .pipe(gulp.dest 'public')

# アプリロジック、underscore moduleをbundle.jsへ
b = browserify(entries)
b.plugin('flexi-require', {
  require: ['underscore']

  external: ['*']
})
b.bundle()
  .pipe(source 'bundle.js')
  .pipe(gulp.dest 'public')

※実際にはwatchifyの対応やbundle-common.jsを必要時にだけbundleしてる等の対応をしてる為もう少し複雑になっています。

ファイル構成

root
├── gulpscripts                        - gulp用スクリプト置き場
|   ├── ast-parser.coffee              - コードのパース処理を行う(get-requires-from-filesで使う)
|   ├── get-requires-from-files.coffee - ファイルからrequire文字列を取得する
|   ├── gulp-callback.coffee           - gulpのストリームの流れからcallbackを呼ぶ
|   └── to-relative-path.coffee        - 絶対パスを相対パスへ
├── bower.json          - Bowerパッケージ
├── package.json        - nodeパッケージ
├── non_package_modules - 野良module
|   └── jquery-2.1.3.js - (あえてパッケージ管理をしていない)
└── gulpsfile.coffee - gulpメイン

flexi-requireを作った経緯

このプラグインは、node_modules以外に対応した使われているmoduleをbundleファイルに含めるプラグインです。

Browserifyでnode_modules以外のmoduleも扱うプラグインは他にもbrowserify-bowerdebowerify等がありますが、browserify-bowerは使われていないmoduleも含めると動作になっており、bundleファイルの不要な肥大化が起こります、その為未使用のmoduleを取り除くには設定値側のメンテが必要になってしまいます。

debowerifyはその心配がないのですが、こちらはtransformに渡すプラグインとなっており、コード内のrequire文字列を直接書き換えてしまう為、bundleファイルを分割した際にaliasが変わっている為に参照が切れる、という問題が起こります。

flexi-requireはこれらの問題を解決する為に作成しています。

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