a blog for those who code

Thursday, 25 May 2017

Require NPM module in browser using Browserify

In this post we will be discussing about Browserify which helps you to use node-style require() to organize your browser code and load modules installed by npm. Browserify lets you use require in the browser the same way you will use it in Node. Browserify will recursively analyze all the require calls and create a bundle which you can serve in the browser using a single <script> tag.

Browserify is useful because it will help you to easily bring in and manage necessary dependencies, handling all the file linking thus you need not have to download the dependencies from various websites, placing them into a local dev folder and manually linking them into your html via script tags.

Install Browserify

To install Browserify you need node and npm installed on your computer. Once you have node and npm installed you can use the below command to install browserify :

npm install -g browserify

The above command installs Browserify and makes it available system-wide.


Lets Write an HTML file called browserifyTest.html with below contents

<!DOCTYPE html>
<html lang="en">
  <title>Browserify Test</title>

  <div id="response"></div>
  <script src="browserifyTest.js"></script>

Where we have referenced a file called browserifyTest.js whose contents are shown below :

var randomString = require('randomstring');
document.getElementById('response').innerHTML = randomString.generate();

When you run this file in the browser you will get the error as shown below :

So now we will use browserify to convert the JavaScript File to another JavaScript Bundle which will allow us to use require in browser. Browserify bundle up browserifyTest.js by taking note of all the files you require and then include the source of those files in the bundle and also does the same thing for its depenedencies.

browserify browserifyTest.js -o browserifyBundle.js

Then we will be refrencing browserifyBundle.js instead of browserifyTest.js. Once done you can get the required result when you refresh the browser.

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment