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.
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._ = _
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>
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!
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: