How to Use NPM Modules in Your Browser in Three Steps

How to Use NPM Modules in Your Browser in Three Steps

Quickly testing out NPM modules
Ferenc Almasi β€’ 2022 January 19 β€’ Read time 2 min read
If you 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...
  • twitter
  • facebook
JavaScript

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.


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:

Copied to clipboard!
const _ = require('lodash')

window._ = _
main.js

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 _.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScriptinfo Remove ads

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:

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

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
  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.