Have successfully bundled a module collection of Javascript classes into a single library using browserify. But I need to define _
and Backbone
as global modules and wonder if that's the best way.
MyLib is mostly a Backbone collection which requires other submodules:
var _ = require('lodash');
var Backbone = require('backbone');
if (typeof window !== 'undefined') Backbone.$ = window.$;
var foo = require('foo'), bar = require('bar');
module.exports = Backbone.Collection.extend({ ... my library... });
Because Backbone and Underscore are bigger and more general, would like not to bundle them but treat them as external dependencies. So in package.json
, am using browserify-shim
to exclude them:
...
"browserify": {
"transform": [
"browserify-shim"
]
},
"browserify-shim": {
"lodash": "global:_",
"backbone": "global:Backbone"
}
The module loads fine in the browser, as _
gets defined as global variables:
<script src="/javascripts/underscore.js"></script>
<script src="/javascripts/mylib.js"></script>
<script type="text/javascript">
console.log(new MyLib()); // loads fine standalone or via require.js
</script>
But in Node.js, the browserify-bundled module looks for these external dependencies in an object called global
var _ = require("lodash");
var MyLib = require("./libs/mylib");
This fails with TypeError: Cannot call method 'isEqual' of undefined
because _
is undefined. Inside mylib.js
at the top I see the line:
var _ = (typeof window !== "undefined" ? window._ : typeof global !== "undefined" ? global._ : null)
However, I can get it to work by defining the dependencies globally like so:
var _ = GLOBAL.global._ = require("lodash");
var MyLib = require("./libs/mylib");
But this creates global variables, which many strongly discourage in this post: node.js global variables?
Is there a better way to include external dependencies for Browerify modules in Node.js?