Defining global variable for Browserify

29,532

Solution 1

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')

Solution 2

First of all, for your example David is correct. Include all dependencies in every module you need it in. It's very verbose, but there is no compile time magic going on which alleviates all sorts of anti patterns and potential future problems.

The real answer.

This isn't always practical. Browserify accepts an option called insertGlobalVars. On build, each streamed file is scanned for identifiers matching the key names provided and wraps the module in an IIFE containing arguments that resolve each identifier that is not assigned within the module. This all happens before the dependency tree is finalized, which allows you to use require to resolve a dependency.

TLDR

Use insertGlobalVars option in Browserify.

browserify({
  insertGlobalVars: {
    spine: function(file, dir) {
      return 'require("spine")';
    }
  }
});

For every file scanned, if an identifier spine exists that's not assigned, resolve as require("spine").

Share:
29,532
sebastiannm
Author by

sebastiannm

Updated on June 16, 2020

Comments

  • sebastiannm
    sebastiannm about 4 years

    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.

  • CheapSteaks
    CheapSteaks over 9 years
    With common dependencies like jQuery and lodash/underscore, it becomes annoying to clutter half your files with require boilerplate when you're working on large projects. Glad to have the alternatives
  • Dtipson
    Dtipson about 9 years
    The idea though, is that each of those files is a completely defined unit such that you could theoretically take it out of one project and put it in another, and it's still clear what its dependencies are and (sometimes) even where to find them. Obviously you can still work around that if you just want to get the absolute smallest files possible, but it helps to think of it as documentation rather than clutter, per se.