Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How browserify makes Node.js modules to work in the browser?

Ii really can't understand some work behind browserify. When using pure JavaScript modules it seems "easy" to convert it to browser code, even if with many dependencies.

But browserify does more:

Many npm modules that don't do IO will just work after being browserified. Others take more work.

Many node built-in modules have been wrapped to work in the browser, but only when you explicitly require() or use their functionality.

When you require() any of these modules, you will get a browser-specific shim.

And again:

  • process.nextTick(), __dirname, and __filename node-isms work
  • get browser versions of the node core libraries events, stream, path, url, assert, buffer, util, querystring, http, vm, and crypto when you require() them

So... process.nextTick(), __dirname inside the browser... even http? This doesn't make sense to me... how __dirname is supposed to work inside a browser?

like image 709
gremo Avatar asked May 24 '13 16:05

gremo


People also ask

What is Browserify in Node JS?

Browserify in the command line Browserify helps you modularize your client side Javascript code using Nodejs require style. It also supports transforming Nodejs modules on npm to browser compatible ones. You can install browserify using npm Writing code with browserify is pretty easy and familiar with Nodejs developers.

What are the benefits of using Node JS on a browser?

Being able to call Node.js modules from JavaScript running on the browser can present many benefits because you can exploit the Node.js modules for your client side JavaScript applications without having to use a server with Node.js just because you need to implement a functionality that's already available as a Node.js module.

How to install Browserify on Linux?

So first of all lauch your command line terminal and type the famous npm install command to install browserify: Next you should install the module you want to use or to convert to browser compatible script Next in main.js require the module as you do normally with node.js modules:

How to Browserify node and npm packages?

To browserify Node and npm packages, for example react on npm, use the browserify APIs and pipe it to vinyl source and gulp dest like this.


1 Answers

process.nextTick() simply runs a callback later.
In a browser, this is simulated using setTimeout(func, 0), setImmediate, or requestAnimationFrame().

__dirnamne and __filename are simply variables that browserify injects at compile-time based on the original path to the file.

like image 80
SLaks Avatar answered Nov 02 '22 09:11

SLaks