LoginSignup
7
7

More than 5 years have passed since last update.

BrowserifyでNodeコアモジュールを置き換える

Posted at

Browserifyでbundleするとき、requireしたNodeコアモジュールも結合される。ほとんどのコードはブラウザ上でも動くが、IOの発生するモジュールのみ同じインターフェースを持つブラウザ向けモジュールに置換される。

Browserifyのrequireしたモジュールを結合する仕組みは、コアモジュールでも同じなので、-rオプションで置き換えの対象とすることができる。例えばrequire('http')するとhttp-browserifyに置換されるが、これをforkしたモジュールを使ってbundleすることもできる。

$ npm install MisumiRize/http-browserify
http-browserify@1.7.0 node_modules/http-browserify
├── inherits@2.0.1
└── Base64@0.2.1

$ browserify app.js -r http-browserify:http > bundle.js

単純に考えればrequireの仕組みはコアモジュールとそれ以外とで同じなので、-rで何も問題なかった。JavaScriptからだとこう書く。

browserify(['./app.js'])
  .require('http-browserify', {expose: 'http'})
  .bundle(function(err, src) {
    console.log(src);
  });
7
7
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
7
7