How to create a standalone browser package exporting directly to a window?

I want to create a standalone package for the browser that attaches the exported objects directly to the window object, and not nested under the shell object attached to the window .

By doing this, the browser ignores the window:

 browserify main.js --standalone window > bundle.js 

The main.js file is as follows:

 var ModuleA = require('./module-a.js'); var ModuleB = require('./module-b.js'); module.exports = { ModuleA: ModuleA, ModuleB: ModuleB } 

I want both modules to be exposed directly in the global namespace: window.ModuleA and window.ModuleB .

The documentation does not provide an obvious solution.

You can help?

+8
browserify
source share
2 answers

This should work:

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

You can also use window instead of global .

+5
source share

The argument for --standalone should be the name of the global variable that you want to assign to the module. In your example, you are using a “window”, which is likely to cause some strange things on your site.

Instead of forcing modules into the global scope (some developers may not want them there because of conflicts), follow these steps:

browserify main.js --standalone TheModulesAB > bundle.js

Then you can download bundle.js and reference your modules as follows:

 TheModulesAB.A //module-a.js TheModulesAB.B //module-b.js 
+1
source share

All Articles