require('modules')
in the browser
Use a node-style require()
to organize your browser code
and load modules installed by npm.
browserify will recursively analyze all the require()
calls in your app in
order to build a bundle you can serve up to the browser in a single <script>
tag.
Whip up a file, main.js
with some require()s
in it. You can use relative
paths like './foo.js'
and '../lib/bar.js'
or module paths like 'gamma'
that will search node_modules/
using
node's module lookup algorithm.
var foo = require('./foo.js');
var bar = require('../lib/bar.js');
var gamma = require('gamma');
var elem = document.getElementById('result');
var x = foo(100) + bar('baz');
elem.textContent = gamma(x);
Export functionality by assigning onto module.exports
or exports
:
module.exports = function (n) { return n * 111 }
Now just use the browserify
command to build a bundle starting at main.js
:
$ browserify main.js > bundle.js
All of the modules that main.js
needs are included in the bundle.js
from a
recursive walk of the require()
graph using
required.
To use this bundle, just toss a <script src="bundle.js"></script>
into your
html!
With npm do:
npm install -g browserify
Usage: browserify [entry files] {OPTIONS}
Standard 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 Replace a file with an empty stub. Files can be globs.
--exclude, -u Omit a file from the output bundle. Files can be globs.
--external, -x Reference a file from another bundle. Files can be globs.
--transform, -t Use a transform module on top-level files.
--command, -c Use a transform command on top-level files.
--standalone -s Generate a UMD bundle for the supplied export name.
This bundle works with other module systems and sets the name
given as a window global if no module system is found.
--debug -d Enable source maps that allow you to debug your files
separately.
--help, -h Show this message
For advanced options, type `browserify --help advanced`.
Specify a parameter.
Advanced Options:
--insert-globals, --ig, --fast [default: false]
Skip detection and always insert definitions for process, global,
__filename, and __dirname.
benefit: faster builds
cost: extra bytes
--insert-global-vars, --igv
Comma-separated list of global variables to detect and define.
Default: __filename,__dirname,process,Buffer,global
--detect-globals, --dg [default: true]
Detect the presence of process, global, __filename, and __dirname and define
these values when present.
benefit: npm modules more likely to work
cost: slower builds
--ignore-missing, --im [default: false]
Ignore `require()` statements that don't resolve to anything.
--noparse=FILE
Don't parse FILE at all. This will make bundling much, much faster for giant
libs like jquery or threejs.
--no-builtins
Turn off builtins. This is handy when you want to run a bundle in node which
provides the core builtins.
--no-commondir
Turn off setting a commondir. This is useful if you want to preserve the
original paths that a bundle was generated with.
--bare
Alias for both --no-builtins, --no-commondir, and sets --insert-global-vars
to just "__filename,__dirname". This is handy if you want to run bundles in
node.
--deps
Instead of standard bundle output, print the dependency array generated by
module-deps.
--list
Print each file in the dependency graph. Useful for makefiles.
--extension=EXTENSION
Consider files with specified EXTENSION as modules, this option can used
multiple times.
--global-transform, --g
Use a transform module on all files after any ordinary transforms have run.
Passing arguments to transforms:
For -t and -g, you may use subarg syntax to pass options to transforms as the
second parameter after the filename. For example:
-t [ foo -x 3 --beep ]
will call the `foo` transform for each applicable file by calling:
foo(file, { x: 3, beep: true })
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:
- assert
- buffer
- console
- constants
- crypto
- domain
- events
- http
- https
- os
- path
- punycode
- querystring
- stream
- string_decoder
- timers
- tty
- url
- util
- vm
- zlib
Additionally if you use any of these variables, they will be defined in the bundled output in a browser-appropriate way:
- process
- Buffer
- global - top-level scope object (window)
- __filename - file path of the currently executing file
- __dirname - directory path of the currently executing file
You can just as easily create bundle that will export a require()
function so
you can require()
modules from another script tag. Here we'll create a
bundle.js
with the through
and duplexer modules.
$ browserify -r through -r duplexer -r ./my-file.js:my-module > bundle.js
Then in your page you can do:
<script src="bundle.js"></script>
<script>
var through = require('through');
var duplexer = require('duplexer');
var myModule = require('my-module');
/* ... */
</script>
If you prefer the source maps be saved to a separate .js.map
source map file, you may use
exorcist in order to archieve that. It's as simple as:
$ browserify main.js --debug | exorcist bundle.js.map > bundle.js
Learn about additional options here.
If browserify finds a require
d function already defined in the page scope, it
will fall back to that function if it didn't find any matches in its own set of
bundled modules.
In this way you can use browserify to split up bundles among multiple pages to
get the benefit of caching for shared, infrequently-changing modules, while
still being able to use require()
. Just use a combination of --external
and
--require
to factor out common dependencies.
For example, if a website with 2 pages, beep.js
:
var robot = require('./robot.js');
console.log(robot('beep'));
and boop.js
:
var robot = require('./robot.js');
console.log(robot('boop'));
both depend on robot.js
:
module.exports = function (s) { return s.toUpperCase() + '!' };
$ browserify -r ./robot > static/common.js
$ browserify -x ./robot.js beep.js > static/beep.js
$ browserify -x ./robot.js boop.js > static/boop.js
Then on the beep page you can have:
<script src="common.js"></script>
<script src="beep.js"></script>
while the boop page can have:
<script src="common.js"></script>
<script src="boop.js"></script>
You can use the API directly too:
var browserify = require('browserify');
var b = browserify();
b.add('./browser/main.js');
b.bundle().pipe(process.stdout);
var browserify = require('browserify')
Create a browserify instance b
from the entry main files
or opts.entries
.
files
can be an array of files or a single file.
For each file
in files
, if file
is a stream, its contents will be used.
You should use opts.basedir
when using streaming files so that relative
requires will know where to resolve from.
You can also specify an opts.noParse
array which will skip all require() and
global parsing for each file in the array. Use this for giant libs like jquery
or threejs that don't have any requires or node-style globals but take forever
to parse.
opts.extensions
is an array of optional extra extensions for the module lookup
machinery to use when the extension has not been specified.
By default browserify considers only .js
and .json
files in such cases.
opts.basedir
is the directory that browserify starts bundling from for
filenames that start with .
.
opts.commondir
sets the algorithm used to parse out the common paths. Use
false
to turn this off, otherwise it uses the
commondir module.
opts.builtins
sets the list of builtins to use, which by default is set in
lib/builtins.js
in this distribution.
opts.pack
sets the browser-pack implementation to use. The opts.pack()
should return a transform stream that accepts objects of the form that
module-deps generates. Simplifed, this
is roughly:
{"id":"1","source":"console.log('beep boop')","deps":{}}
{"id":"2","source":"require('./boop.js')","deps":{"./boop.js":"1"}}
By default, opts.pack
uses
browser-pack:
require('browser-pack')({ raw: true, sourceMapPrefix: '//@' });
opts.externalRequireName
defaults to 'require'
in expose
mode but you can
use another name.
You can give browserify a custom opts.resolve()
function or by default it uses
browser-resolve.
Note that if files do not contain javascript source code then you also need to specify a corresponding transform for them.
Add an entry file from file
that will be executed when the bundle loads.
Make file
available from outside the bundle with require(file)
.
The file
param is anything that can be resolved by require.resolve()
.
file
can also be a stream, but you should also use opts.basedir
so that
relative requires will be resolvable.
Use the expose
property of opts to specify a custom dependency name.
require('./vendor/angular/angular.js', {expose: 'angular'})
enables require('angular')
Bundle the files and their dependencies into a single javascript file.
Return a readable stream with the javascript file contents or
optionally specify a cb(err, src)
to get the buffered results.
When opts.insertGlobals
is true, always insert process
, global
,
__filename
, and __dirname
without analyzing the AST for faster builds but
larger output bundles. Default false.
When opts.detectGlobals
is true, scan all files for process
, global
,
__filename
, and __dirname
, defining as necessary. With this option npm
modules are more likely to work but bundling takes longer. Default true.
When opts.debug
is true, add a source map inline to the end of the bundle.
This makes debugging easier because you can see all the original files if
you are in a modern enough browser.
When opts.standalone
is a non-empty string, a standalone module is created
with that name and a umd wrapper.
You can use namespaces in the standalone global export using a .
in the string
name as a separator. For example: 'A.B.C'
opts.insertGlobalVars
will be passed to
insert-module-globals
as the opts.vars
parameter.
Prevent file
from being loaded into the current bundle, instead referencing
from another bundle.
Prevent the module name or file at file
from showing up in the output bundle.
Instead you will get a file with module.exports = {}
.
Prevent the module name or file at file
from showing up in the output bundle.
If your code tries to require()
that file it will throw unless you've provided
another mechanism for loading it.
Transform source code before parsing it for require()
calls with the transform
function or module name tr
.
If tr
is a function, it will be called with tr(file)
and it should return a
through-stream
that takes the raw file contents and produces the transformed source.
If tr
is a string, it should be a module name or file path of a
transform module
with a signature of:
var through = require('through');
module.exports = function (file) { return through() };
You don't need to necessarily use the through module, this is just a simple example.
Here's how you might compile coffee script on the fly using .transform()
:
var coffee = require('coffee-script');
var through = require('through');
b.transform(function (file) {
var data = '';
return through(write, end);
function write (buf) { data += buf }
function end () {
this.queue(coffee.compile(data));
this.queue(null);
}
});
Note that on the command-line with the -c
flag you can just do:
$ browserify -c 'coffee -sc' main.coffee > bundle.js
Or better still, use the coffeeify module:
$ npm install coffeeify
$ browserify -t coffeeify main.coffee > bundle.js
If opts.global
is true
, the transform will operate on ALL files, despite
whether they exist up a level in a node_modules/
directory. Use global
transforms cautiously and sparingly, since most of the time an ordinary
transform will suffice. You can also not configure global transforms in a
package.json
like you can with ordinary transforms.
Global transforms always run after any ordinary transforms have run.
Register a plugin
with opts
. Plugins can be a string module name or a
function the same as transforms.
plugin(b, opts)
is called with the browserify instance b
.
For more information, consult the plugins section below.
Return a readable stream of the dependency array generated by module-deps.
browserify uses the package.json
in its module resolution algorithm just like
node. If there is a "main"
field, browserify will start resolving the package
at that point. If there is no "main"
field, browserify will look for an
"index.js"
file in the module root directory. Here are some more
sophisticated things you can do in the package.json:
There is a special "browser" field you can set in your package.json on a per-module basis to override file resolution for browser-specific versions of files.
For example, if you want to have a browser-specific module entrypoint for your
"main"
field you can just set the "browser"
field to a string:
"browser": "./browser.js"
or you can have overrides on a per-file basis:
"browser": {
"fs": "level-fs",
"./lib/ops.js": "./browser/opts.js"
}
Note that the browser field only applies to files in the local module and like
transforms it doesn't apply into node_modules
directories.
You can specify source transforms in the package.json in the
browserify.transform
field. There is more information about how source
transforms work in package.json on the
module-deps readme.
For example, if your module requires brfs, you can add
"browserify": { "transform": [ "brfs" ] }
to your package.json. Now when somebody require()
s your module, brfs will
automatically be applied to the files in your module without explicit
intervention by the person using your module. Make sure to add transforms to
your package.json dependencies field.
When a file is resolved for the bundle, the bundle emits a 'file'
event with
the full file
path, the id
string passed to require()
, and the parent
object used by
browser-resolve.
You could use the file
event to implement a file watcher to regenerate bundles
when files change.
When .bundle()
is called, this event fires with the bundle
output stream.
When a transform is applied to a file, the 'transform'
event fires on the
bundle stream with the transform stream tr
and the file
that the transform
is being applied to.
For some more advanced use-cases, a transform is not sufficiently extensible. Plugins are modules that take the bundle instance as their first parameter and an option hash as their second.
Plugins can be used to do perform some fancy features that transforms can't do.
For example, factor-bundle is a
plugin that can factor out common dependencies from multiple entry-points into a
common bundle. Use plugins with -p
and pass options to plugins with
subarg syntax:
browserify x.js y.js -p [ factor-bundle -o bundle/x.js -o bundle/y.js ] \
> bundle/common.js
For a list of plugins, consulte the browserify-plugin tag on npm.
There is a wiki page that lists the known browserify transforms.
If you write a transform, make sure to add your transform to that wiki page and
add a package.json keyword of browserify-transform
so that
people can browse for all the browserify
transforms on npmjs.org.
There is a wiki page that lists the known browserify tools.
If you write a tool, make sure to add it to that wiki page and
add a package.json keyword of browserify-tool
so that
people can browse for all the browserify
tools on npmjs.org.
MIT