skip to content
Just Change Direction

How to use packages in the Chrome console

/ 1 min read

I regularly debug simple stuff in the Chrome console but sometimes the code I want to debug relies on a npm package. I could always write a script or throwaway package but sometimes I find this trick more handy.

You have a couple of options:

  1. If the package has named exports
var script = document.createElement("script");
// Just import the whole thing
script.src = "https://unpkg.com/[email protected]/dayjs.min.js";
document.head.appendChild(script);
// Now I can use the named exports in the console e.g.
const myDate = dayjs("2024-09-04");
  1. If the package only has a default export
var script = document.createElement("script");
// Note: because I am using an ESM module, I have to specify that
script.type = "module";
script.src = "https://esm.sh/[email protected]";
document.head.appendChild(script);
script.onload = () => {
import("https://esm.sh/[email protected]").then((module) => {
// Set the default export to the name `confetti` on the window object
window.confetti = module.default;
console.log("confetti is now available globally");
});
};
// Now I can use confetti e.g.
confetti();