Browserify
Make node-style require() work in the browser, as if by magic!
Browserify generates a single static bundle that you can drop into your application with a single<script>
tag. You can use browserify with any kind of web stack that can host up static files.
Just write anentry.js
to start with somerequire()
s in it:
var foo = require('./foo');
window.onload = function () {
document.getElementById('result').innerHTML = foo(100);
};
and then afoo.js
:
var bar = require('./bar');
module.exports = function (x) {
return x * bar.coeff(x) + (x * 3 - 2)
};
and then abar.js
:
exports.coeff = function (x) {
return Math.log(x) / Math.log(2) + 1;
};
Now you need to build this. You can either:
- use the browserify CLI tool
- use the middleware
- use the API
using the CLI tool
browserify entry.js -o browserify.js
Then just throw a<script src="http://t.zoukankan.com/browserify.js"></script>
into your HTML!
using the middleware
var express = require('express');
var app = express.createServer();
app.listen(8080);
var bundle = require('browserify')(__dirname + '/entry.js');
app.use(bundle);
Then just throw a<script src="http://t.zoukankan.com/browserify.js"></script>
into your HTML!
using the API
See below.
features at a glance
-
usenpmmodules in the browser
-
require()
s work browser-side just as they do in node -
coffee script just works™ — just require('./beans.coffee') or whichever
-
lots of node builtins just work™:
- require('events')
- require('path')
- require('vm')
- require('http')
- require('assert')
- require('url')
- require('buffer')
- require('util')
- require('querystring')
-
lots of ways to compile
-
watch mode automatically recompiles your bundle when files change
-
debug mode for real line numbers (just subtract 2)
command-line usage
Usage: node ./bin/cli.js [entry files] {OPTIONS}
Options:
--outfile, -o Write the browserify bundle to this file.
If unspecified, browserify prints to stdout.
--require, -r A module name or file to bundle.require()
Optionally use a colon separator to set the target.
--entry, -e An entry point of your app
--ignore, -i Ignore a file
--alias, -a Register an alias with a colon separator: "to:from"
Example: --alias 'jquery:jquery-browserify'
--cache, -c Turn on caching at $HOME/.config/browserling/cache.json or use
a file for caching.
[default: true]
--debug, -d Switch on debugging mode with //@ sourceURL=...s. [boolean]
--plugin, -p Use a plugin. Use a colon separator to specify additional
plugin arguments as a JSON string.
Example: --plugin 'fileify:["files","."]'
--prelude Include the code that defines require() in this bundle.
[boolean] [default: true]
--watch, -w Watch for changes. The script will stay open and write updates
to the output every time any of the bundled files change.
This option only works in tandem with -o.
--verbose, -v Write out how many bytes were written in -o mode. This is
especially useful with --watch.
--help, -h Show this message
methods
var browserify = require('browserify');
var b = browserify(opts={})
Return a middleware with attached methods that will host up a browserified script atopts.mount
or"http://t.zoukankan.com/browserify.js"
if unspecified.
opts
may also contain these fields:
- require - calls
b.require()
- ignore - calls
b.ignore()
- entry - calls
b.addEntry()
- filter - registers a "post" extension using
b.register()
- watch - set watches on files, see below
- cache - turn on caching for AST traversals, see below
- debug - turn on source mapping for debugging with
//@ sourceURL=...
in browsers that support it
Ifopts
is a string, it is interpreted as arequire
value.
Any query string afteropts.mount
will be ignored.
watch :: Boolean or Object
Set watches on files and automatically rebundle when a file changes.
This option defaults to false. Ifopts.watch
is set to true, default watch arguments are assumed or you can pass in an object to pass along as the second parameter tofs.watchFile()
.
cache :: Boolean or String
Ifcache
is a boolean, turn on caching at$HOME/.config/browserify/cache.json
.
Ifcache
is a string, turn on caching at the filename specified bycache
.
bundle events
b
bundles will also emit events.
'syntaxError', err
This event gets emitted when there is a syntax error somewhere in the build process. If you don't listen for this event, the error will be printed to stderr.
'bundle'
In watch mode, this event is emitted when a new bundle has been generated.
b.bundle()
Return the bundled source as a string.
b.require(file)
Require a file or files for inclusion in the bundle.
Iffile
is an array, require each element in it.
Iffile
is a non-array object, map an alias to a package name. For instance to be able to maprequire('jquery')
to the jquery-browserify package, you can do:
b.require({ jquery : 'jquery-browserify' })
and the same thing in middleware-form:
browserify({ require : { jquery : 'jquery-browserify' } })
To mix alias objects with regular requires you could do:
browserify({ require : [ 'seq', { jquery : 'jquery-browserify' }, 'traverse' ])
In practice you won't need tob.require()
very many files since all therequire()
s are read from each file that you require and automatically included.
b.ignore(file)
Omit a file or files from being included by the AST walk to hunt downrequire()
statements.
b.addEntry(file)
Append a file to the end of the bundle and execute it without having torequire()
it.
Specifying an entry point will let yourequire()
other modules without having to load the entry point in a<script>
tag yourself.
If entry is an Array, concatenate these files together and append to the end of the bundle.
b.filter(fn)
Transform the source using the filter functionfn(src)
. The return value offn
should be the new source.
b.register(ext, fn)
Register a handler to wrap extensions.
Wrap every file matching the extensionext
with the functionfn
.
For everyfile
included into the bundlefn
gets called for matching file types asfn.call(b, body, file)
for the bundle instanceb
and the file content stringbody
.fn
should return the new wrapped contents.
Ifext
is unspecified, execute the wrapper for every file.
Ifext
is 'post', execute the wrapper on the entire bundle.
Ifext
is 'pre', call the wrapper function with the bundle object before the source is generated.
Ifext
is an object, pull the extension fromext.extension
and the wrapper functionfn
fromext.wrapper
. This makes it easy to write plugins likefileify.
Coffee script support is just implemented internally as a.register()
extension:
b.register('.coffee', function (body) {
return coffee.compile(body);
});
b.use(fn)
Use a middleware plugin,fn
.fn
is called with the instance objectb
.
b.prepend(content)
Prepend unwrapped content to the beginning of the bundle.
b.append(content)
Append unwrapped content to the end of the bundle.
b.alias(to, from)
Alias a package name from another package name.
b.modified
Contains a Date object with the time the bundle was last modified. This field is useful in conjunction with thewatch
field described in thebrowserify()
to generate unique<script>
src
values to force script reloading.
package.json
In order to resolve main files for projects, the package.json "main" field is read.
If a package.json has a "browserify" field, you can override the standard "main" behavior with something special just for browsers.
The "browserify" field can be a string that points to the browser-specific "main" file or it can be an object with a "main" field in it.
compatability
process
Browserify exports a fauxprocess
object with these attributes:
- nextTick(fn) - usesthe postMessage trickfor a faster
setTimeout(fn, 0)
if it can - title - set to 'browser' for browser code, 'node' in regular node code
require('events')
require('assert')
require('url')
require('buffer')
require('buffer_ieee754')
require('stream')
require('vm')
All the goodness of node'srequire('vm')
has been emulated with iframe trickery. This functionality is made available by thevm-browserifyproject.
require('http')
Implement the client side of the node http api using thehttp-browserifyproject.
require('path')
The posix functions from thepath
module have been included except forexists()
andexistsSync()
. Justrequire('path')
!
__dirname
The faux directory name, scrubbed of true directory information so as not to expose your filesystem organization.
__filename
The faux file path, scrubbed of true path information so as not to expose your filesystem organization.
recipes
use an npm module in the browser
First install a module:
npm install traverse
Then write anentry.js
:
var traverse = require('traverse');
var obj = traverse({ a : 3, b : [ 4, 5 ] }).map(function (x) {
if (typeof x === 'number') this.update(x * 100)
});
console.dir(obj);
then build it!
browserify entry.js -o bundle.js
then put it in your html
<script src="http://t.zoukankan.com/bundle.js"></script>
and the entry.js will just run andrequire('traverse')
will just work™.
convert a node module into a browser require-able standalone file
Usingnpm
>= 1.0 from the commandz line: Install thetraverse
package locally (into thenode_modules
folder)
npm install traverse
Utilizebrowserify
to... browserify the package
npm install -g browserify
browserify --require traverse -o bundle.js
Look at the files! There is a new one:bundle.js
. Now go into HTML land:
<script src="http://t.zoukankan.com/bundle.js"></script>
<script>
var traverse = require('traverse');
</script>
read more
browserify: browser-side require() for your node.js
ad-hoc browserify CDN!
jquery-browserify
install
Usingnpmjust do:
npm install browserify
to install into your project's node_modules directory, or if you want to use the command-line tool, install globally with:
npm install -g browserify
test
To run the node tests with tap, do:
npm test
To run thetestlingtests, create abrowserlingaccount then:
cd testling
./test.sh
- require('events')
- require('path')
- require('vm')
- require('http')
- require('assert')
- require('url')
- require('buffer')
- require('util')
- require('querystring')