Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RequireJS in the browser: how can I log a variable without modifying my code first?

I'm using RequireJS in my browser. I have some JS loaded by a script tag, something like:

requirejs(["jquery", "shared", function($, shared) {
  var foo='bar';
}

I would like to print the current value of 'foo' from a JS console in the Chrome Dev Tools. How can I do this?

Edit 2: This question was originally very vaguely worded - sorry about that. To clarify, I do not wish to stop using RequireJS, pollute global, or know in advance what it is I want to debug.

like image 269
mikemaccana Avatar asked Mar 26 '26 23:03

mikemaccana


2 Answers

Set a breakpoint in Chrome or Firebug to break at the point of your closure. Foo will then be available to the console until you resume script execution.

edit: Scope will still matter. If the variable is private within a member of shared, you'll need to set a break in shared.js instead, e.g. if we assume shared.js contains:

var shared = {
    myFunc: function() {
        var foo = 'bar';
        // break here
    }
}
like image 168
hedgehog Avatar answered Mar 29 '26 13:03

hedgehog


If I understand the question, the whole point of using RequireJS is not to use global variables!

Therefore I define a console.js module like this:

define(function() {
  var nativeConsole = {};
  try {
    // for IE 8/9
    if (!window.console) {
      window.console = {
        log:   function() {},
        debug: function() {},
        info:  function() {},
        warn:  function() {},
        error: function() {}
      };
    }
    nativeConsole = console;
  // Firefox throws an exception if you access the console object and it doesn't exist. Wow!
  } catch (e) { }
  return nativeConsole;
});

Then use it like this:

requirejs(["jquery", "console", function($, console) {
  var foo='bar';
  console.warn("foo = " + foo);
}
like image 33
Steve Eynon Avatar answered Mar 29 '26 13:03

Steve Eynon