7

I'm using Angular2 and underscore,

import * as _ from 'underscore';

and I want to use the underscore library in Chrome console window too. Even I do break on a middle of the code, and try to use , but I got ' is not defined' error.

Is it possible I can use the underscore in Chrome console window? how?

Expert wanna be
  • 10,218
  • 26
  • 105
  • 158

2 Answers2

22

You can simply do it by adding underscore.js script onto the head of your page:

1) Go to Chrome Console of the page you wish to debug.

2) Run this script to import underscorejs so that the console starts recognizing _ commands:

var s = document.createElement('script'); 
s.type = 'text/javascript';
s.src = 'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js';
document.head.appendChild(s);

Alternatively, you can save such import script code inside a snippet for further usage:

Go to source tab, select snippet sub-tab, click on + to add a new snippet, then add the following code and save:

(function () {
  if (typeof window._ === 'undefined') {    
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.src = 'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js';
    document.head.appendChild(s);
  }
}());

This way, whenever you need to debug a page using an external library, you can simply add it by running its correspondent snippet!

hd84335
  • 8,815
  • 5
  • 34
  • 45
  • See [this question](https://stackoverflow.com/questions/51926317/using-underscore-js-in-chrome-console) - what does `window.R` refer to? Did you mean `window._`? – CertainPerformance Aug 20 '18 at 08:22
  • If you get a `failed to load` error I tried using an updated minified link from underscore and it worked out fine. I used: `https://underscorejs.org/underscore-min.js` – ConstantFun May 29 '19 at 07:27
  • when I run the snippet the underscore js file download freezes on 'pending'. When I let my page completely load then it finished downloading the underscore script, but by then I'm no longer debugging. I can't find a way to get the underscore script to finish loading while I'm debugging. – Post Impatica Aug 06 '19 at 20:01
  • Never mind. I got it to work by putting another break point much earlier in my code. – Post Impatica Aug 06 '19 at 20:09
1

To use underscore.js into chrome console for practice. Step 1: Open https://underscorejs.org/ Step 2: Now open console and we can use underscore function to it.