Dave Sanders Dave Sanders - 2 months ago 15
Javascript Question

Access javascript objects from dev console after bundling

I'm working on a React app and learning the ropes. I have a SPA where my dev environment is all running in Docker, and is using Gulp + Watchify, Browserify, and Babelify to bundle up all my JS(X) code and get it to the browser as a "bundle.js".

Everything works well, except I cannot access objects like React and ReactDOM from my Chrome developer tools. I'm sure this is because they are being "hidden" due to how they are being bundled up, but I'm not sure how to fix that or gain access to them. I can always "window.ReactDOM = ReactDOM" in my code, but that seems like the dumb way to go, and I foresee wanting to play with more code in the console.

I noted that I can add "debugger" to my code, and these objects are available when the code is paused, but once it runs I can't access the objects.

How are these objects being hidden away, and is there a sane way to get access to them besides breakpoints?


How they are hidden: It is often times useful to not leak variables to the window/global scope. This is important because different files and different libraries could have the same variable names and conflict with each other in. A very simple trick usually used is doing something like:

// Runs an inline anonymous function
     /// Make your variables and run your code here ...
     var a = 1; // Only accessible in this function
console.log(a) // Undefined

^ The above is a common 'wrapper' to see around a regular JS file.

If you examine the output of webpack or another bundler, they take this a step further and make a closure for each file. So the bundle will look something like:

   var files = [
      function(module, require){ var ReactDOM = require('react-dom')... /* file one code */}
      function(module, require){ ... module.exports = localReactDomVar ... }

   // Webpack magic runs each file and recursively gets dependencies on calls to require...

TLDR: Each module is intentionally hidden and is anonymous anyway until the point in your code at which you do var React = require('react'). If you need access to React and ReactDOM in your console, there is no better way than window.React = React etc.