Defining global variable for Browserify

sebastiannm picture sebastiannm · May 5, 2014 · Viewed 28.6k times · Source

I'm using SpineJS (which exports a commonjs module) and it needs to be available globally because I use it everywhere, but It seems like I have to do Spine = require('spine') on every file that uses Spine for things to work.

Is there any way to define Spine once to make it globally available?

PS: I'm using Spine as an example, but I'm in general wondering about how to do this with any other library.

Answer

David Bonnet picture David Bonnet · May 6, 2014

Writing Spine = require('spine') in each file is the right way to do.

Yet, there are several possibilities by using the global or window object (browserify sets the global object to window, which is the global namespace):

  • in spine.js: global.Spine = module.exports
  • in any other .js file bundled by browserify: global.Spine = require('spine')
  • in a script tag or an .js file referenced by the .html file, after the spine.js file: window.Spine = require('spine')