2

Our team develops browser side javascript app. We use angularjs as framework and some helper libraries in global namespace. For example: underscore.

We carried out a large piece of code (input/output data tranformation) into a standalone library for unit testing reasons.

Now i try to use browserify with this library. The question is about what the best way to exclude from bundle shared (with main app) dependences (underscore for example). I tried 2:

  1. Using --external. I have to create bundle from underscore and use it for all code stuff in app. If i understood right this way seems inconvenient.
  2. Using browser property in package.json to replace underscore with stub:

    module.exports = _;

I believe that there is more clean approach, but where is it?

user3414982
  • 357
  • 1
  • 4
  • 15

1 Answers1

2

You don't have to use --external or something like that. Just include the library like this:

<script src="external/lib.js"></script>

then you can use it within your bundle (without require).

BUT: In my opinion you shouldn't mix global libs with browserify. All benefits of browserify will decrease drastically this way.

Contras:

  • more than one file to include
  • worse readability cause fewer `require` statements

RECOMMEND:

create one bundle with all external libs and install them as npm modules.

npm install --save angular
npm install --save lodash

create external bundle:

browserify -r angular -r lodash > external/libs.js

you only have to bundle it once because they should never change. then create main app bundle without external modules:

browserify --no-bundle-external app.js > bundle.js

then include these two bundles to your page:

<script src="external/libs.js"></script>
<script src="bundle.js"></script>
marcel
  • 2,967
  • 1
  • 16
  • 25
  • Problem is that i have to use `require('./external/lib')` for testing purpose in node environment. – user3414982 Jun 23 '15 at 12:53
  • I don't know whether one can use angular with commonjs modules... It has its own approach for modules management. For this reason i would like to keep the rest of app as is. – user3414982 Jun 23 '15 at 13:45
  • ok. NOTE: i have often heard about problems when using `browserify` with `commonjs` modules. Sry, but i cannot help with that. – marcel Jun 23 '15 at 13:54
  • Do we have to remove require from all files then when using external libs? – vini Apr 11 '16 at 13:52
  • Yes. When you include the libraray directly in your html file (and don't use something like browserify to bundle/scope your code) you have the remove the hole require statement, `var lib = require("external/lib.js");`. The library should be accessible in the global space. You just have to use it. – marcel Apr 11 '16 at 19:21