- In my previous post we have learnt about commonJS module style of exporting methods and bundle it for client/browser using Browserify.
- To generate the browser version of Node JS module we need to issue a command Browserify source.js –o destination.js.For each change of the JavaScript code we have to execute this command again and again.To simplify this process a new tool named watchify is created which runs in the background and listens to changes to the script and updates the destination/bundle JavaScript.
- In this demo,”We will learn a new tool named watchify installation and use it for our development”.
- The directory and file structure that we have created is as follows.
- To install watchify we need to execute npm install –g watchify command in the terminal.The following screenshot shows the terminal with watchify installation in progress.
- To start the watchify watcher for watching changes to script use the following command watchify demo.js -d -o bundle.js –v.The following screenshot shows the terminal to start the watchify.
- Now we have modified few script to check whether watchify is working or not.The following screenshot shows the log messages in the console for the changes in script.
- Now lets checkout how to use watchify with npm build.Let’s generate a package.json file with npm init command.The following screenshot shows the terminal with npm initialization in progress.
- After successful initialization of package.json file the updated structure looks like following screenshot.
- Now we can add 2 task build and watch inside package.json.The following code shows the content of package.json file.
{ "name": "BrowserifyDemoPart3", "version": "0.0.0", "description": "BrowserifyDemoPart3", "scripts":{ "build": "browserify demo.js -o bundle.js", "watch": "watchify demo.js -o bundle.js --debug --verbose" }, "main": "bundle.js", "author": "Sandeep", "license": "ISC" }
- Now we can run the watchify by using command npm run watch command in terminal.The following screenshot shows the npm watch task in terminal.
- Now we can generate Browserify build by using npm run build command.The following screenshot shows the terminal with npm build in execution.
- The demo code can be downloaded from the following link.