Browserify : How to use Node.js require dependencies in Browser as Javascipt

How to get Browserify

Use the following to download browserify.

npm install -g browserify

Automate Browserify Dependency

You can also create a package.json file by the following command.

npm init

This will create a basic package.json file. now run the command

npm install --save browserify

--save option will download the file and save its reference in package.json. Now on other machine you just need to run the command npm install and it will download the browserify plugin and save it on your machine.

This will download the browserify in node_modules folder. Now we can use browserify to download our node dependencies. For this we will first create a .js file named require.js, you can name it anything you want.

Let's see a sample file.

angular = require('angular');
ngSanitize = require('angular-sanitize');

Now, to make browserify work you should have all these modules installed on your system under node_modules.

npm install angular
npm install angular-sanitize

Now, you can package both files in a single file by running the following command.

browserify require.js > destFile.js

The above command will compile all the files in require.js to the destination file specified after > . You can specify both relative and absolute path.

So, now you do not need to include both angular.js and angualr-sanitize.js files in your html, rather you just need to include destFile.js.

Browserify reference to included file.

If you want a reference to your js file you can update your js file as follows.

// to include markdown dependency
global.md = require('markdown-it');

Now you can get the reference of your markdown library as md and use it in javascript or jquery as follows

var markdown = md();

This will make an instance of markdown and assign to variable markdown.

No comments:

Powered by Blogger.