Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 539
Bryan Head Avatar asked Apr 23 '13 14:04

Bryan Head


People also ask

What is browserify used for?

Browserify is an open-source JavaScript bundler tool that allows developers to write and use Node. js-style modules that compile for use in the browser.

When should I use Browserify?

Browserify solves the problems of having too many JS files referenced in your HTML, inability to use Node modules in the browser, and inability to reference your own modules in your own code. Watchify streamlines the process of bundling your files and will make a change every time you change a JS file in your project.

Can a module have multiple exports?

You can only have one default export for any given module, but this does not mean you are then limited to only exporting one function, it simply means you can only export one default export. As long as you only have one default export, you can still have as many named exports as you like.

How do module exports work?

All functions related to a single module are contained in a file. Module exports are the instructions that tell Node. js which bits of code (functions, objects, strings, etc.) to export from a given file so that other files are allowed to access the exported code.


1 Answers

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 
like image 176
karellm Avatar answered Sep 19 '22 01:09

karellm