If you want to test a npm package directly in the browser, there is a way to do this!
How?
The tric is to load a javascript file programmatically in the developers console:
const script = document.createElement('script');
script.src = 'localhost:666/bundle.js';
document.body.appendChild(script);
Only what is bundle.js?
That's a bundle that we will create in a minute with browserify
.
And what is localhost:666/
That's a local server that you will serve (later in this tutorial), because chrome browser does not allow local files to be loaded.
Let's start building
You can replace cheerio
with any npm package you like (but not all of them work in the browser)
- Open up a new directory
npm init -y
-
npm i -D browserify http-server
(as dev dependencies) -
npm i cheerio
(or any package you want to use) touch main.js
-
code .
(launch visual code studio) - in main.js edit the following:
const cheerio = require("cheerio");
window.cheerio = cheerio; // this makes it available in the console later
- in package.json add the following:
"scripts": {
"serve": "browserify main.js -o build/bundle.js && http-server -p 666 build/"
},
npm run build
- open browser
- check if this loads: localhost:666/bundle.js
- if so copy paste this to Chrome's developers console (on any page)
const script = document.createElement('script');
script.src = 'localhost:666/bundle.js';
document.body.appendChild(script);
- Now play around in your developer console with the npm package, in our case:
const $ = cheerio.load(document.body.innerHTML);
$('a');
PS: Not all npm packages work, I tried request
but it gave an error in the developer console. But nowadays I would recommend to use the new standard fetch
for this.
Github: You can clone this repo also!
Top comments (0)