Making jQuery, Backbone, etc global variables in Browserify

1.2k views Asked by At

I have a relatively large app built with Backbone and Marionette. That means that at the top of every file I have something like:

var _ = require('underscore');
var $ = require('jquery');
var Backbone = require('backbone');
Backbone.$ = $;
var Marionette = require('backbone.marionette');

I know that part of the idea of Browserify is that there are no globals but this seems like a lot of unnecessary boilerplate. What I'd like is to have jQuery, Backbone, Underscore, and Marionette load a global variables as they normally do and just assume everywhere in that they are available. Is there a way to do this in browserify?

1

There are 1 answers

1
YPCrumble On

My preferred option would to take advantage of ES6 (ECMAScript 2015) features and make a file called something like libraries.js:

var _ = require('underscore');
var $ = require('jquery');
var Backbone = require('backbone');
Backbone.$ = $;
var Marionette = require('backbone.marionette');

module.exports = { _, $, Backbone, Marionette };

...then at the top of your other files you could just use:

// libraries.js should be in /node_modules/, or use ... = require('/path/to/libraries.js');
// This requires ES6 (ECMAScript 2015)
const { _, $, Backbone, Marionette } = require('libraries'); 

This is a little different from what you're asking for, but I don't think you actually want to make these variables pollute the global object of your app. You just want to reduce boilerplate.

If you wanted these variables available to other code in the global scope, you could remove the var statements from libraries.js (maybe name it globals.js in that case) and they'd appear on the window object.