- The require() method is so popular and used by NodeJS developer to load modules.
- 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.
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.