10

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

2
  • Can you create a function in your script, and within the variable scope, that returns the value of the variable? If you want to debug it you could use console.log or just add breakpoints to view the value during execution. Commented Apr 2, 2014 at 21:18
  • 1
    I could do window.m , but managing n quantity of variables imagine how big would that be ! and yes, I can console.log from there, but that would having me refreshing every time... Commented Apr 2, 2014 at 21:52

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Jethik: It was the correct answer, but I added an edit for clarification.
3
var m= require('m');

window.M= m;

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.