How to access a variable declared in a browser script

So I have this script 'source.js'.

var m = require("somemodule"); 

And then I built it using a browser:

 $ browserify source -o build.js 

Is there a way to access m in the Chrome Chrome console? Due to node.js encapsulation, m not global ...

+7
javascript browserify
source share
2 answers

the browser wraps things in closure, in particular, to limit the scope (e.g. node.)

Use a global (e.g. node) or window to embed things in a common area. You can also require things again (e.g. node) to get a cached area (same object.)

So this is a trick for sharing a region in a node or browser:

 var m = require('m'); m.cool = true; // in another file var m = require('m'); console.log(m.cool); 

To raise it to global space, you can add global.m = require('m') to any script that is required in this chain for the browser to add it to the global namespace (which allows the window in the browser.)

You can also use browserify --standalone for somemodule if you want to open it directly.

+1
source share
 var m= require('m'); window.M= m; 

after the browser, var moduleM = new M();

0
source share

All Articles