How do I load NPM packages in browser dev tools console?

512 Views Asked by At

Doing it this way:

const _ = await import('https://unpkg.com/lodash')

gives me a strange object with single Symbol(Symbol.toStringTag) prop valued "Module".

Note 1: I'm aware of the trick

import _ from 'lodash'
window._ = _

in your code, please give your answer only if the import works directly from browser's dev tools console.

Note 2: I'm also aware that this question has been asked many times. I read through all the answers, they either do not work nowadays or are inapplicable because of Note 1. So I decided to ask it again.

2

There are 2 best solutions below

1
Vivick On BEST ANSWER

This is a lodash specific thing I recon as it uses an IIFE

await import("https://unpkg.com/lodash");
console.log(_, window._);
0
Jos de Jong On

Here a small helper function that I find handy to load ESM packages from NPM in the dev console:

/**
 * Load an ESM package from npm in your JavaScript environment.
 *
 * Loads packages from https://www.npmjs.com/ via the CDN https://www.jsdelivr.com/
 *
 * Usage:
 * 
 *     const lodash = await npm('lodash-es')
 *     const lodash = await npm('lodash-es@4')
 *     const lodash = await npm('[email protected]')
 *
 *     lodash.uniq([1, 3, 2, 1, 2, 2]) // [1, 3, 2]
 */
async function npm(name) {
  return await import(`https://cdn.jsdelivr.net/npm/${name}/+esm`)
}

See gist: https://gist.github.com/josdejong/3d176fa90efa36ed51ab6a4e8810074e