import or require any library in browser console

10.7k Views Asked by At

While debugging application most of the time I feel like it would hve easier if I could include any library into browser console and try some of the function from that libraty.

Now in modern javascript/es6/es6/typescript world is there any thing short and quick available to to import a script instantly to the brower so that it can be used to directly

Example

While debugging, if I want Observable I should be able to do something like this

import {Observable} from 'rxjs/Observable';  //typescript way
const Observable= require('rxjs/Observable'); // require way

But these are not working.

already explored dynamic <script> tag

I already explore old way to dynamically using the <script> tag like below but its dificult for large number of libs and also not elegant

var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
// ... give time for script to load, then type (or see below for non wait option)
jQuery.noConflict();
1

There are 1 best solutions below

2
On

Some browsers (including Chrome) can use snippets in console, either as built-in features or extensions.

One-liner script to do this is

document.head.appendChild(Object.assign(
    document.createElement('script'),
    { src: '...' }
));

Considering that most websites already have jQuery loaded (even if they don't, this can be handled by browser extensions, such as Chrome jQuery Injector) it can be shortened to:

$.getScript('...');

Any piece of code that should be always available in console can also be exposed as global function with user scripts (Tampermonkey in Chrome, etc), with some limitations imposed by user script security.

This will probably will be possible with dynamic import(), which is currently stage 3 proposal and isn't implemented in browsers.


A suitable solution that works for most major libraries the one may be curious to quickly experiment with is to navigate to official library website and open the console. Due to the fact that the websites often provide live examples, relevant variables are exposed to global scope. Known examples are $ for jQuery, angular for AngularJS, ng for Angular, Rx for RxJS, moment for Moment.js...