Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
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).
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);
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!
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 > bundle.js
Then in your page you can do:
<script src="bundle.js"></script>
<script>
var through = require('through');
var duplexer = require('duplexer');
/* ... */
</script>
If browserify finds a require
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);
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 Omit a file from the output bundle.
--external, -x Reference a file from another bundle.
--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
--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.
--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.
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:
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.
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.
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()
.
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.
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.
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
browserify uses the package.json
in its module resolution algorithm just like
node, but there is a special
"browser" field you can set to override file
resolution for browser-specific versions.
You can specify source transforms in the package.json in the browserify.transforms field. There is more information about how source transforms work in package.json on the module-deps readme.
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.
Here is a list of known source transforms:
brfs - inline
fs.readFileSync()
calls with file contents
coffeeify - compile
.coffee
files to javascript automatically
icsify - compile
.iced
IcedCoffeeScript files to javascript automatically
caching-coffeeify - coffeeify version that caches previously compiled files to optimize the compilation step
decomponentify - use component client packages seamlessly with browserify.
debowerify - use bower client packages more easily with browserify.
deAMDify - translate AMD modules to Node-style modules automatically
hbsfy - precompile handlebars templates to javascript functions automatically
rfileify - inline rfile(path)
calls with file contents
(also supports ruglify
and any other rfile
derivatives)
liveify - compile livescript files to javascript automatically
es6ify - compile ES6 files to ES5 javascript automatically
turn - minimal modules for a hypothetical es6 with lua's return
rfolderify - turn calls to rfolder into a map of requires of the files in the thing
If you want to efficiently re-compile the bundle automatically when you edit files, you can use watchify.
If you are using express or connect, you can use enchilada or browserify-middleware to host your bundles as middleware.
If you want a standalone web server for development that will create bundles on demand, check out browservefy.
With npm do:
npm install -g browserify
MIT
FAQs
browser-side require() the node way
The npm package browserify receives a total of 1,392,637 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
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.