Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browserify to load dependencies from global scope's require instead of expecting them to be bundled up together

I'm developing library A and library B, B depending on A. I would like, using browserify, to bundle them up independently, so in my browser I could do:

var A = require("A");
var B = require("B");

I would like to bundle them up independently as I'm also developing library C that only depends on A and if A is included in B then it won't be accessible by C, and if A is in B and C, I've got duplicates.

So I start with browserifying library A:

browserify -r ./src/A.js:A -o build/A.js

Which works perfectly fine, I can distribute A and other people can develop their applications with it.

Then I browserify library B:

browserify -r ./src/B.js:B -o build/B.js

But I now have A two times, A being loaded independently in the browser and once again packaged with B. So I use the -i option from browserify to prevent it from being included:

browserify -r ./src/B.js -o build/B.js -i A

But then, when B requires A, it gets an empty object {} instead of the library. The library A though is still available from the global scope by doing require("A").

I tried the externalise thing with -x but then I can't require my library from the global scope anymore.

I managed to get the behaviour that I wanted by hacking the generated output of B, forcing the module resolution to get A from a previous require, which makes me think that there can be an easy solution, but I can't find it.

I'm using browserify 2.18.1

like image 821
Olivier Avatar asked Jun 29 '13 18:06

Olivier


1 Answers

Two ways of looking at it :

  • Think of B like jquery-ui and A as jquery. It's upto the users to include the jquery into the DOM, if they wish to use jquery-ui. So while building B do not require A at all.

  • Document the fact that B has A built into it. The users who use B should simply not include A at all. In this scenario - you obviously need to require A and bundle up B with A together.

  • In general if you have 2 browserified bundles, with common parts, that are being imported in the SAME page then you have already fallen into the problem of bundle organization/dependency, what components go in what etc. Something in the basics of that needs to be reviewed/changed

like image 185
Zasz Avatar answered Oct 12 '22 07:10

Zasz