Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create standalone browserify bundle exporting directly to window?

Tags:

browserify

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?

like image 908
Razvan Caliman Avatar asked Sep 16 '15 09:09

Razvan Caliman


People also ask

How do I bundle a standalone module with Browserify?

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.

Is it possible to use Browserify as a standalone option?

@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.

Why does Browserify generate an empty module when I run it?

@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.

How can i Improve my Browserify development?

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.


1 Answers

This should work:

global.ModuleA = require('./module-a.js');
global.ModuleB = require('./module-b.js');

You could also use window instead of global.

like image 178
Walter Avatar answered Oct 20 '22 01:10

Walter