browser-side require() the node.js way
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.
If you're new to browserify, check out the browserify handbook and the resources on browserify.org.
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 browserify
…
…
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:
Additionally, if you use any of these variables, they will be defined in the bundled output in a browser-appropriate way:
You can just as easily create a 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 achieve 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 required 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.js > 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>
This approach using -r and -x works fine for a small number of split assets,
but there are plugins for automatically factoring out components which are
described in the
partitioning section of the browserify handbook.
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')
browserify([files] [, opts])Returns a new browserify instance.
files String, file object, or array of those types (they may be mixed) specifying entry file(s). opts Object.files and opts are both optional, but must be in the order shown if both are
passed.
Entry files may be passed in files and / or opts.entries.
External requires may be specified in opts.require, accepting the same formats
that the files argument does.
If an entry file is a stream, its contents will be used. You should pass
opts.basedir when using streaming files so that relative requires can be
resolved.
opts.entries has the same definition as files.
opts.noParse is an 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.transform is an array of transform functions or modules names which will
transform the source code before the parsing.
opts.ignoreTransform is an array of transformations that will not be run,
even if specified elsewhere.
opts.plugin is an array of plugin functions or module names to use. See the
plugins section below for details.
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.paths is an array of directories that browserify searches when looking
for modules which are not referenced using relative path. Can be absolute or
relative to basedir. Equivalent of setting NODE_PATH environmental variable
when calling browserify command.
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.fullPaths disables converting module ids into numerical indexes. This is
useful for preserving the original paths that a bundle was generated with.
opts.builtins sets the list of built-ins to use, which by default is set in
lib/builtins.js in this distribution.
opts.bundleExternal boolean option to set if external modules should be
bundled. Defaults to true.
When opts.browserField is false, the package.json browser field will be
ignored. When opts.browserField is set to a string, then a custom field name
can be used instead of the default "browser" field.
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.ignoreMissing is true, ignore require() statements that don't
resolve to anything.
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'. The global export will be sanitized
and camel cased.
Note that in standalone mode the require() calls from the original source will
still be around, which may trip up AMD loaders scanning for require() calls.
You can remove these calls with
derequire:
$ npm install derequire
$ browserify main.js --standalone Foo | derequire > bundle.js
<script src="bundle.js"></script>
<script type="text/javascript">
// Now you can address `Foo` by name in your HTML document
Foo.bar();
</script>
opts.insertGlobalVars will be passed to
insert-module-globals
as the opts.vars parameter.
opts.externalRequireName defaults to 'require' in expose mode but you can
use another name.
opts.bare creates a bundle that does not include Node builtins, and does not
replace global Node variables except for __dirname and __filename.
opts.node creates a bundle that runs in Node and does not use the browser
versions of dependencies. Same as passing { bare: true, browserField: false }.
Note that if files do not contain javascript source code then you also need to specify a corresponding transform for them.
All other options are forwarded along to module-deps and browser-pack directly.
Add an entry file from file that will be executed when the bundle loads.
If file is an array, each item in file will be added as an entry file.
Make file available from outside the bundle with require(file).
The file param is anything that can be resolved by require.resolve(),
including files from node_modules. Like with require.resolve(), you must
prefix file with ./ to require a local file (not in node_modules).
`file