Creating global variables jQuery, Backbone, etc. In Browserify

I have a relatively large application built with Backbone and Marionette. This means that at the top of each file I have something like:

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

      

I know part of Browserify's idea is that there are no globals, but that seems like a lot of unnecessary boilerplate. I would like jQuery, Backbone, Underscore and Marionette to load globals as they usually do and just assume they are available everywhere. Is there a way to do this in a browser?

+3


source to share


1 answer


My preferred option would be to take advantage of ES6 features (ECMAScript 2015) and make a file 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 can simply 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 slightly different from what you are asking for, but I don't think you really want these variables to pollute global

your application object . You just want to shrink the template.

If you want these variables to be available to other code in the global scope, you could remove the instructions var

from library.js (perhaps call it in this case globals.js

) and they will appear on the window

object.

-1


source







All Articles