How to Use NPM Modules in Your Browser in Three Steps

If you simply want to test out some NPM modules right inside your browser without setting up an entire app, you can use Browserify in three simple steps to use NPM modules.

JavaScript Course

1. Install Browserify and the Tools You Need

First, make sure you have Browserify installed globally. You can run browserify in your terminal to see if the command is available. If it's not, run:

npm i -g browserify

Don't forget to install the NPM modules that you would like to use. For this, we can create an empty folder and run npm init -y to quickly generate a package.json file and start adding packages. For this example, I'm going to be using the famous Lodash library:

npm i lodash

2. Require Your Modules in a JavaScript File

Create a new JavaScript file in your folder (I called it main.js) and require in the modules that you would like to use inside the browser:

const _ = require('lodash')

window._ = _
main.js
Copied to clipboard!

Make sure you assign the required module to the window so that it will be exposed as a global variable. This way we can reach the entire Lodash library from the console using _.


3. Compile the File With Browserify

All that's left to do is to bundle the NPM modules and load them into an HTML file that we can open in the browser. Using browserify, run the following command in your terminal:

browserify main.js -o bundle.js

This will take main.js and recursively bundle your NPM modules together into a bundle.js file. Then in an empty index.html, using a script tag, require in the bundled version:

<script src="./bundle.js"></script>
index.html
Copied to clipboard!

Open this HTML file in your browser, and now you can typeΒ _ inside the console to access the entire Lodash library. Here you get access to the NPM modules you needed to reach. Thank you for reading through, happy coding!

How to Publish Your First NPM Package JavaScript Course Remove ads Remove ads

πŸ“š Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. β˜•

Get access Support us
Remove ads Read more on
Ezoicreport this ad Remove ads
Remove ads
πŸŽ‰ Thank you for subscribing to our newsletter. x