browserify / browser-pack

pack node-style source files from a json stream into a browser bundle
Other
174 stars 58 forks source link

Why not avoid the same module run multiple times when more than one other modules require it. #64

Closed Jinjiang closed 9 years ago

Jinjiang commented 9 years ago

For example, when both A and B require X, the code in X will be executed twice although the bundle doesn't include the code twice. That's not very convenient in browser if X need same config or data for both A and B. This situation is very common for me.

I found that the module with same content will be bundled as {"dup": firstAppearedModuleNumber}. So I suppose we cound just change these lines below in prelude.js

modules[name][0].call(m.exports, function(x){
    var id = modules[name][1][x];
    return newRequire(id ? id : x);
},m,m.exports,outer,modules,cache,entry);

into:

if (modules[name][1].dup) { // that means module duplicated right?
    cache[name] = cache[modules[name][1].dup]
}
else {
    modules[name][0].call(m.exports, function (x) {
        var id = modules[name][1][x]
        return newRequire(id ? id : x)
    }, m, m.exports, outer, modules, cache, entry)
}

But I'm not sure that works fine.

Thx

zertosh commented 9 years ago

This is on purpose and it happens here https://github.com/substack/node-browserify/blob/f9c2561/index.js#L640-L662.

There are two kinds of duplications:

  1. Two files have the same content but are meant to be different modules. For example, consider a simple module.exports = {};. That code can exist in say configA.js and configB.js. Duduping is a space saving optimization only. If browserify didn't run the code twice, then it'd be the same as if you'd only required one of the files - clearly breaking things.
  2. Two files have the same content but are meant to be the same module. This is your case. This happens most often when dependencies have a common dependency (like underscore or whatever), which has the same content but it's on two different places. The solution to this is to simply run npm dedupe. npm will consolidate semver compatible versions of deps. So when two different modules require the same dep, they get the exact same file path.
Jinjiang commented 9 years ago

get it! Thx