- The require() method is so popular and used by NodeJS developer to load modules.
- Browserify provides the feature of using require() method for the client side JavaScript and bundling up of all dependencies together.
- Browserify provides a way to use the NPM modules (published for NodeJS server side programming) in the client/browser environment.This statement hinting to a new area of application development where code base can be shared to both server-client and termed ad Isomorphic JavaScript.
- In this demo, “We will learn to install Browserify and checkout the usage by a simple example”.
- To install Browserify use the following command npm install –g Browserify in the terminal.
- The following screenshot shows the terminal with Browserify installation in progress.
- To demonstrate a sample use of Browserify we have installed a node module called operator which provides basic mathematical operations like addition,subtraction etc.The following screenshot shows the installation operator npm module in a terminal.
- We have created a JavaScript file my-script.js which uses the operator module to find out the addition of 2 number 5 and 4 and logs the result in the console.The following code shows the content of my-script.js.
var operator = require('operator'), result = operator.add(5,4); console.log(result);
- For the reference the following screenshot shows the updated file structure for this demo.
- Now we can run the my-script.js file using node command.The following screenshot shows execution of node command on my-script.js file.
- The previous screenshot shows the my-script.js runs perfectly in NodeJS environment.Now it is time for the magical Browserify.The following screenshot shows the terminal with Browserify command generating bundle.js from my-script.js which can be used by the client/browser environment.
- Now we can create a demo.html file and include the generated bundle.js file in a script element.The updated file structure is as follows.
- The following code shows the content of demo.html file which includes the generated bundle.js file.
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Browserify Demo Part1</title> </head> <body> <h1></h1> <script src="bundle.js"></script> </body> </html>
- The following screenshot shows the output of the demo.html in the browser environment.We can clearly see the log message in chrome developer console which results 9 from addition of 5 and 4.
- The demo code can be downloaded from the following URL.