Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

require returns empty object when using browserify

I have a very simple module that I am bundling with Browserify. I want to use that bundle both in the browser as well as in node. In node, it works just fine if I require the non-bundled module; however, if I require the browserified bundle, require returns an empty object. Here's a reproduction:

Simple module

function Foo(bar) {
    this.bar = bar;
}

module.exports = Foo;

Test script

var Foo = require("./foo"); // not bundled with Browserify
var Foob = require("./foob"); // bundled with Browserify

console.log("Foo =", Foo);
console.log("Foob =", Foob);

Executed thusly

browserify foo.js -o foob.js
node foo-test.js 

Output

Foo = function Foo(bar) {
    this.bar = bar;
}
Foob = {}

You can see that Foo (the non-bundled version) is the expected function but Foob (the bundled version) is a sad and empty object.

So the question is why isn't the browserified module working in node?

Clarification: I'm using browserify to bundle my webapp and I use its paths options to simplify paths in my app's require statements and avoid relative path hell. However, I'm trying to use tap to do unit testing, but it doesn't seem to have a similar configuration feature. Because of this, trying to require non-bundled files when using tap causes everything to break.

like image 520
Justin Johnson Avatar asked Feb 14 '26 15:02

Justin Johnson


1 Answers

I found a way around this. The solution is to use browserify's --standalone option when bundling. This will add the necessary module.exports statement in the bundled output.

like image 90
Justin Johnson Avatar answered Feb 17 '26 04:02

Justin Johnson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!