I want to create a standalone browserify bundle which attaches the exported objects directly to the window
object, not nested under a wrapper object attached to window
.
Doing this, browserify ignores the window:
browserify main.js --standalone window > bundle.js
The main.js
file looks like this:
var ModuleA = require('./module-a.js');
var ModuleB = require('./module-b.js');
module.exports = {
ModuleA: ModuleA,
ModuleB: ModuleB
}
I want both modules exposed directly in the global namespace: window.ModuleA
and window.ModuleB
.
The documentation doesn't provide an obvious solution.
Can you help?
The key part of bundling standalone modules with Browserify is the --s option. It exposes whatever you export from your module using node's module.exports as a global variable. The file can then be included in a <script> tag. You only need to do this if for some reason you need that global variable to be exposed.
@Matas Vaitkevicius's answer with Browserify's standalone option is correct (@thejh's answer using the window global variable also works, but as others have noted, it pollutes the global namespace so it's not ideal). I wanted to add a little more detail on how to use the standalone option.
@jackyrudetsky Make sure you're passing --standalone your-module-name. If you forget that --standalone takes an argument, browserify might silently generate an empty module since it couldn't find it. IMO this should be the accepted answer.
Use tinyify for optimized, tree-shaked bundles in production environments. Use --debug when creating bundles to have Browserify automatically include Source Maps for easy debugging. Check out tools like Beefy or run-browser which make automating browserify development easier.
This should work:
global.ModuleA = require('./module-a.js');
global.ModuleB = require('./module-b.js');
You could also use window
instead of global
.
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