
Security News
Crates.io Implements Trusted Publishing Support
Crates.io adds Trusted Publishing support, enabling secure GitHub Actions-based crate releases without long-lived API tokens.
browserify
Advanced tools
Browserify is a tool for Node.js that enables developers to use the require() function from Node in the browser. It bundles up all of your JavaScript files and dependencies into a single file that can be served to the browser. It allows for modular code in the client-side environment by leveraging the CommonJS module pattern.
Bundle modules for the browser
This feature allows you to bundle all your JavaScript files and dependencies into a single file. The code sample demonstrates how to create a bundle starting with 'main.js' and output it to 'bundle.js'.
const browserify = require('browserify');
const fs = require('fs');
let b = browserify();
b.add('main.js');
b.bundle().pipe(fs.createWriteStream('bundle.js'));
Transformations
Browserify can apply transformations to the files as they are added to the bundle. This is useful for tasks like compiling ES6 syntax to ES5 using Babel, as shown in the code sample.
const browserify = require('browserify');
const babelify = require('babelify');
browserify('./src/app.js')
.transform(babelify, { presets: ['@babel/preset-env'] })
.bundle()
.pipe(process.stdout);
Plugins
Browserify can be extended with plugins that can add additional functionality. In the code sample, the watchify plugin is used to automatically re-bundle the file whenever changes are detected.
const browserify = require('browserify');
const watchify = require('watchify');
const b = browserify('./src/app.js', { plugin: [watchify] });
b.on('update', bundle);
function bundle() {
b.bundle().pipe(fs.createWriteStream('bundle.js'));
}
Webpack is a powerful module bundler that can transform front-end assets like HTML, CSS, and images where Browserify is strictly for JavaScript. Webpack also has a larger plugin ecosystem and can split bundles more efficiently.
Parcel is a web application bundler that offers a zero-configuration setup. It is faster than Browserify due to its multi-core processing capability and it also handles a variety of assets like HTML, CSS, and images out of the box.
Rollup is a module bundler for JavaScript which uses the new standardized format for code modules included in the ES6 revision. It is known for its efficient bundling, as it generates a smaller bundle by eliminating unused code (tree shaking).
Make node-style require() work in the browser, as if by magic!
Just write an entry.js
to start with some require()
s in it:
var foo = require('./foo');
window.onload = function () {
document.getElementById('result').innerHTML = foo(100);
};
and then a foo.js
:
var bar = require('./bar');
module.exports = function (x) {
return x * bar.coeff(x) + (x * 3 - 2)
};
and then a bar.js
:
exports.coeff = function (x) {
return Math.log(x) / Math.log(2) + 1;
};
Now you need to build this. You can either:
browserify entry.js -o browserify.js
Then just throw a <script src="/browserify.js"></script>
into your HTML!
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="/browserify.js"></script>
into your HTML!
See below.
use npm modules 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('querystring')
lots of ways to compile
watch mode automatically recompiles your bundle when files change
Usage: browserify [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]
--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
Specify a parameter.
var browserify = require('browserify');
Return a middleware with attached methods that will host up a browserified
script at opts.mount
or "/browserify.js"
if unspecified.
opts
may also contain these fields:
b.require()
b.ignore()
b.addEntry()
b.register()
If opts
is a string, it is interpreted as a require
value.
Any query string after opts.mount
will be ignored.
Set watches on files and automatically rebundle when a file changes.
This option defaults to false. If opts.watch
is set to true, default watch
arguments are assumed or you can pass in an object to pass along as the second
parameter to fs.watchFile()
.
If cache
is a boolean, turn on caching at
$HOME/.config/browserify/cache.json
.
If cache
is a string, turn on caching at the filename specified by cache
.
b
bundles will also emit events.
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.
In watch mode, this event is emitted when a new bundle has been generated.
Return the bundled source as a string.
Require a file or files for inclusion in the bundle.
If file
is an array, require each element in it.
If file
is a non-array object, map an alias to a package name.
For instance to be able to map require('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 to b.require()
very many files since all the
require()
s are read from each file that you require and automatically
included.
Omit a file or files from being included by the AST walk to hunt down
require()
statements.
Append a file to the end of the bundle and execute it without having to
require()
it.
Specifying an entry point will let you require()
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.
Transform the source using the filter function fn(src)
. The return value of
fn
should be the new source.
Register a handler to wrap extensions.
Wrap every file matching the extension ext
with the function fn
.
For every file
included into the bundle fn
gets called for matching file
types as fn.call(b, body, file)
for the bundle instance b
and the file
content string body
. fn
should return the new wrapped contents.
If ext
is unspecified, execute the wrapper for every file.
If ext
is 'post', execute the wrapper on the entire bundle.
If ext
is 'pre', call the wrapper function with the bundle object before the
source is generated.
If ext
is an object, pull the extension from ext.extension
and the wrapper
function fn
from ext.wrapper
. This makes it easy to write plugins like
fileify.
Coffee script support is just implemented internally as a .register()
extension:
b.register('.coffee', function (body) {
return coffee.compile(body);
});
Use a middleware plugin, fn
. fn
is called with the instance object b
.
Prepend unwrapped content to the beginning of the bundle.
Append unwrapped content to the end of the bundle.
Alias a package name from another package name.
Contains a Date object with the time the bundle was last modified. This field is
useful in conjunction with the watch
field described in the browserify()
to
generate unique <script>
src
values to force script reloading.
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.
Browserify exports a faux process
object with these attributes:
You can require('events').EventEmitter
just like in node.js code.
All the goodness of node's require('vm')
has been emulated with iframe
trickery and eval()
hacks.
The posix functions from the path
module have been included except for
exists()
and existsSync()
. Just require('path')
!
The faux directory name, scrubbed of true directory information so as not to expose your filesystem organization.
The faux file path, scrubbed of true path information so as not to expose your filesystem organization.
First install a module:
npm install traverse
Then write an entry.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="bundle.js"></script>
and the entry.js will just run and require('traverse')
will just work™.
Using npm
>= 1.0 from the commandz line:
Install the traverse
package locally (into the node_modules
folder)
npm install traverse
Utilize browserify
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="bundle.js"></script>
<script>
var traverse = require('traverse');
</script>
browserify: browser-side require() for your node.js
Using npm just 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
FAQs
browser-side require() the node way
The npm package browserify receives a total of 1,822,144 weekly downloads. As such, browserify popularity was classified as popular.
We found that browserify demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 40 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Crates.io adds Trusted Publishing support, enabling secure GitHub Actions-based crate releases without long-lived API tokens.
Research
/Security News
Undocumented protestware found in 28 npm packages disrupts UI for Russian-language users visiting Russian and Belarusian domains.
Research
/Security News
North Korean threat actors deploy 67 malicious npm packages using the newly discovered XORIndex malware loader.