Browserify resolves the same file multiple times

2019-07-21 03:24发布

问题:

I am facing a strange problem running latest browserify (10.2.4) and gulp. It seems that the same file is being resolved multiple times, and so I don't get the same instance when creating a singleton. I've put a 'debugger' before module.exports and verified it is called twice.

note #1: I have a guess that says that browserify caches the files based on the string, and so when calling relative paths from different places will not have the same string, even though they point to the same place.

note #2: I was using Browserify 3~ until now, and only when I upgraded it started happening.

Example:

Given:

app.js
/folder1/foo.js
/folder2/bar.js

/folder1/foo.js:

function Foo(){}
module.exports = new Foo(); // Creating a singleton

/folder2/bar.js

var foo = require('../folder1/foo');
function Bar(){
// do something with foo
}
module.exports = Bar;

/app.js

var foo = require('./folder1/foo'),
Bar = require('./folder2/bar');
var bar = new Bar();
// Now 'foo' here and 'foo' inside Bar are not the same instance.

回答1:

You should change your architecture like this:

/folder1/foo.js:

function Foo(){}
module.exports = Foo;

/folder2/bar.js

function Bar(foo){
// do something with foo
}
module.exports = Bar;

/app.js

var Foo = require('./folder1/foo'),
var Bar = require('./folder2/bar');
var bar = new Bar(new Foo());

I had the same problem, and i found out that it is simply an impractible architectural style.

EDIT: This way, you have a "singleton", that is just managed by the main component/class (app.js).

For example: Imagine, you have a subcomponent/subclass that needs a config object. -> App.js uses SubComponent.js.

Your way: require 'config' (implemented as singleton) and use it for the component.

Problem: Now you want to add an other SubComponent of the same type that also needs an other config object. It wouldn't work with your solution.

Solution: Let your parent component handle all "singletons" (config objects).