Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a variable declared within browserify script

So I have this script 'source.js'.

var m = require("somemodule");

And then I built it with browserify:

$ browserify source -o build.js

Is there any way to access m within the chrome|firefox console? Because of node.js encapsulation, m is not global...

like image 902
alexserver Avatar asked Apr 02 '14 21:04

alexserver


2 Answers

browserify wraps things in a closure, specifically to limit scope (like node.)

Use global (like node) or window to inject things into a shared scope. You can also require things again (like node)to get the cached scope (the same object.)

So, this is a trick to share a scope in node or browserify:

var m = require('m');
m.cool = true;

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

To hoist it into global space, you can add global.m = require('m') in any script that is required in that browserify build-chain to add it to global namespace (which resolves to window in browserify.)

You can also use browserify --standalone on somemodule, if you want to expose it directly.

like image 53
konsumer Avatar answered Oct 23 '22 02:10

konsumer


var m= require('m');

window.M= m;

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

like image 32
Jethik Avatar answered Oct 23 '22 02:10

Jethik