Question

I thinking of bringing my existing app over to using CommonJS modules and using Browserify to bundle up the modules into one file.

I'm getting my head around writing modules but the one thing I'm a little sceptical before I dive in and start re-writing certain bits, is how can I optimise it slightly so I don't have to include Backbone, Underscore, jQuery and any helper files in in each file, ie.

var Backbone = require('/backbone');
var $ = require('/jquery');
var _ = require('/underscore');

At the top of each file is going to get a little tedious after a while.

Being a complete CommonJS, Browserify n00b, I'm wondering if I'm missing something very obvious somewhere?

Was it helpful?

Solution

The "very obvious thing" you're missing is that you can create globals in Node.js, and in the Browserify environment just the same. Either do it explicitly by using global.Backbone = require('/backbone'), or less explicit by just doing Backbone = require('/backbone') (without var in front).

Note that in the browser, the global object is in fact the window object. However, attaching to the window object would mean you lose compatibility with Node.js, because that typically doesn't have a global variable window defined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top