brunch / commonjs-require-definition

Common.js require definition.
MIT License
13 stars 12 forks source link

Fixes recursion and providing the correct module data. #2

Closed jacwright closed 10 years ago

jacwright commented 10 years ago

This fix allows for two modules to require each other the way Node.js does. By putting the module object in the cache instead of its exports object we allow for returning the correct module.exports even before the initModule function returns.

Example:

some-class.js

function SomeClass() {

}
SomeClass.prototype.doSomething = function() {
  return new AnotherClass()
};
module.exports = SomeClass;
var AnotherClass = require('./another-class');

another-class.js

function AnotherClass() {

}
AnotherClass.prototype.doSomethingElse = function() {
  return new SomeClass()
};
module.exports = AnotherClass;
var SomeClass = require('./some-class');

Currently this results in a Maximum Call Stack Exceeded error. Adding the exports to the cache before calling definition() fixes the recursion, but doesn't provide the correct module.exports inside the recursion. But placing the module in the cache and returning cache[name].exports will always return the correct module at the given point in code. And this is the same behavior as Node.js.

Could you please bump and publish to NPM? Thank you!

paulmillr commented 10 years ago

0.1.2

jacwright commented 10 years ago

Wow, you're good.