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 require
ing the script.
Is it possible to detect if a script is being require
d? 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 require
able and <script src=
able? Is it best to just expose a global in both circumstances?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With