Browserify: Use module.exports if required, otherwise expose global

Bryan Head picture Bryan Head · Apr 23, 2013 · Viewed 30.6k times · Source

I'm considering adopting browserify for some of my projects, but would like to make sure that others don't have to use browserify if they want to use the (bundled) code. The obvious way to do this is to both expose the modules exports through module.exports as well as through a window. global. However, I'd rather not pollute the global namespace for those who are requireing the script.

Is it possible to detect if a script is being required? If it is, then I could do something like:

var mymodule = (function() { ... })();
if (isRequired()) {
  module.exports = mymodule;
} else {
  window.mymodule = mymodule;
}

Note that no matter what, this will be bundled beforehand, so the var mymodule won't be exposing a global. Also, currently I'm using the revealing module pattern, but would be willing to switch to something more appropriate for browserify.

What's the best way to make a module both requireable and <script src=able? Is it best to just expose a global in both circumstances?

Answer

karellm picture karellm · Jan 19, 2014

There is a good article from Forbes Lindesay explaining how to do standalone builds: http://www.forbeslindesay.co.uk/post/46324645400/standalone-browserify-builds

The short version, use the standalone option:

browserify beep.js --standalone beep-boop > bundle.js