Using Node.js modules in the browser
At the beginning of this chapter, we discussed creating universal modules that can run under Node.js or in the browser. There is another way that we can allow our code to run in both environments.
Browserify (http://browserify.org/) allows you to make use of Node.js modules in the browser. It bundles up your code together with its dependencies. It also provides browser-compatible shims to emulate Node.js built-in modules.
You can install Browserify via npm:
> npm install -g browserify
Browserify is typically used to package applications. For example, if we wanted to package our demo usage of autotoc from the previous section, we could run:
> browserify demo.js -o bundle.js
Browserify will create a single JavaScript file containing the code from demo.js
, along with its dependencies and transitive dependencies. If we include this in an HTML page, we can now see it working in the browser console:
You can also use Browserify to generate browser-compatible...