I wanted to try a node module in a browser app that uses global variables to share stuff.

Versions used below

  "superagent": "1.2.0",
  "browserify": "10.2.3",
  "webpack": "1.9.10"

I was thinking about using superagent to do ajax in a browser app that uses globals to access libraries and modules. The slightly opinionated superagent only supports CommonJS.

Two module bundlers that can make a CommonJS-only module available as a global are browserify and webpack.

1. Install the node module

Create a package.json if there isn’t one already. This will be your record of what version of the module was used.

$ npm init -f

-f will accept all the default options of npm init.

Then install the module.

$ npm install superagent -S

2. Create entry file

browserify and webpack will bundle dependencies of the entry file (and their dependencies, and dependencies of their dependencies, etc). In this case a dependency is anything pulled in through a require() call.

The entry file is just a CommonJS passthrough – it exports the module we want to use.

// entry.js
module.exports = require('superagent');

3a. Use browserify

browserify’s --standalone option uses umd to make the resulting bundle work with most JavaScript module systems. A global variable is created if no module system is detected.

The argument to --standalone is the name of the global variable. It’s named request below because that’s the naming convention used in the superagent docs.

$ browserify entry.js --standalone request --outfile superagent-global.js

3b. Or use webpack

The command I use for webpack is similar to browserify.

$ webpack entry.js --output-library request --outfile superagent-global.js

It will default to creating a global variable named by the argument to --output-library. To generate a umd module or any other type, you’d also use --output-library-target and specify the module type.

Final usage

Now in my browser app I can do

<script src="superagent-global.js"></script>
  request.get('/foo').end(function(error, response) {