- Notifications
You must be signed in to change notification settings - Fork0
browser-side require() the node.js way
License
NodeJSTW/node-browserify
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
require('modules')
in the browser
Use anode-stylerequire()
to organize your browser codeand load modules installed bynpm.
browserify will recursively analyze all therequire()
calls in your app inorder to build a bundle you can serve up to the browser in a single<script>
tag.
Whip up a file,main.js
with somerequire()s
in it. You can use relativepaths like'./foo.js'
and'../lib/bar.js'
or module paths like'gamma'
that will searchnode_modules/
usingnode's module lookup algorithm.
varfoo=require('./foo.js');varbar=require('../lib/bar.js');vargamma=require('gamma');varelem=document.getElementById('result');varx=foo(100)+bar('baz');elem.textContent=gamma(x);
Export functionality by assigning ontomodule.exports
orexports
:
module.exports=function(n){returnn*111}
Now just use thebrowserify
command to build a bundle starting atmain.js
:
$ browserify main.js > bundle.js
All of the modules thatmain.js
needs are included in thebundle.js
from arecursive walk of therequire()
graph usingrequired.
To use this bundle, just toss a<script src="bundle.js"></script>
into yourhtml!
Withnpm 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 messageFor 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. --no-bundle-external Turn off bundling of all external modules. This is useful if you only want to bundle your local files. --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. --full-paths Turn off converting module ids into numerical indexes. This is useful for preserving the original paths that a bundle was generated with. --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=MODULE, -g MODULE Use a transform module on all files after any ordinary transforms have run. --plugin=MODULE, -p MODULE Register MODULE as a plugin.Passing arguments to transforms and plugins: For -t, -g, and -p, you may use subarg syntax to pass options to the transforms or plugin function as the second parameter. For example: -t [ foo -x 3 --beep ] will call the `foo` transform for each applicable file by calling: foo(file, { x: 3, beep: true })
Manynpm modules that don't do IO will just work after beingbrowserified. Others take more work.
Many node built-in modules have been wrapped to work in the browser, but onlywhen you explicitlyrequire()
or use their functionality.
When yourequire()
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, theywill be definedin 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 arequire()
function soyou canrequire()
modules from another script tag. Here we'll create abundle.js
with thethroughandduplexer modules.
$ browserify -r through -r duplexer -r ./my-file.js:my-module > bundle.js
Then in your page you can do:
<scriptsrc="bundle.js"></script><script>varthrough=require('through');varduplexer=require('duplexer');varmyModule=require('my-module');/* ... */</script>
If you prefer the source maps be saved to a separate.js.map
source map file, you may useexorcist in order to achieve that. It's as simple as:
$ browserify main.js --debug | exorcist bundle.js.map > bundle.js
Learn about additional optionshere.
If browserify finds arequire
d function already defined in the page scope, itwill fall back to that function if it didn't find any matches in its own set ofbundled modules.
In this way you can use browserify to split up bundles among multiple pages toget the benefit of caching for shared, infrequently-changing modules, whilestill being able to userequire()
. Just use a combination of--external
and--require
to factor out common dependencies.
For example, if a website with 2 pages,beep.js
:
varrobot=require('./robot.js');console.log(robot('beep'));
andboop.js
:
varrobot=require('./robot.js');console.log(robot('boop'));
both depend onrobot.js
:
module.exports=function(s){returns.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:
<scriptsrc="common.js"></script><scriptsrc="beep.js"></script>
while the boop page can have:
<scriptsrc="common.js"></script><scriptsrc="boop.js"></script>
You can use the API directly too:
varbrowserify=require('browserify');varb=browserify();b.add('./browser/main.js');b.bundle().pipe(process.stdout);
varbrowserify=require('browserify')
Create a browserify instanceb
from the entry mainfiles
oropts.entries
.files
can be an array of files or a single file.
For eachfile
infiles
, iffile
is a stream, its contents will be used.You should useopts.basedir
when using streaming files so that relativerequires will know where to resolve from.
opts.noparse
is an array which will skip all require() and global parsing foreach file in the array. Use this for giant libs like jquery or threejs thatdon'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 lookupmachinery 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 forfilenames that start with.
.
opts.commondir
sets the algorithm used to parse out the common paths. Usefalse
to turn this off, otherwise it uses thecommondir module.
opts.fullPaths
disables converting module ids into numerical indexes. This isuseful for preserving the original paths that a bundle was generated with.
opts.builtins
sets the list of builtins to use, which by default is set inlib/builtins.js
in this distribution.
opts.bundleExternal
boolean option to set if external modules should bebundled. Defaults to true.
Whenopts.insertGlobals
is true, always insertprocess
,global
,__filename
, and__dirname
without analyzing the AST for faster builds butlarger output bundles. Default false.
Whenopts.detectGlobals
is true, scan all files forprocess
,global
,__filename
, and__dirname
, defining as necessary. With this option npmmodules are more likely to work but bundling takes longer. Default true.
Whenopts.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 ifyou are in a modern enough browser.
Whenopts.standalone
is a non-empty string, a standalone module is createdwith that name and aumd wrapper.You can use namespaces in the standalone global export using a.
in the stringname as a separator. For example:'A.B.C'
Note that in standalone mode therequire()
calls from the original source willstill be around, which may trip up AMD loaders scanning forrequire()
calls.You can remove these calls withderequire:
$ npm install -g derequire$ browserify main.js --standalone Foo | derequire > bundle.js
opts.insertGlobalVars
will be passed toinsert-module-globalsas theopts.vars
parameter.
opts.externalRequireName
defaults to'require'
inexpose
mode but you canuse another name.
Note that if files do not contain javascript source code then you also need tospecify a corresponding transform for them.
All other options are forwarded along tomodule-depsandbrowser-pack directly.
Add an entry file fromfile
that will be executed when the bundle loads.
Iffile
is an array, each item infile
will be added as an entry file.
Makefile
available from outside the bundle withrequire(file)
.
Thefile
param is anything that can be resolved byrequire.resolve()
.
file
can also be a stream, but you should also useopts.basedir
so thatrelative requires will be resolvable.
Iffile
is an array, each item infile
will be required.
Use theexpose
property of opts to specify a custom dependency name.require('./vendor/angular/angular.js', {expose: 'angular'})
enablesrequire('angular')
Bundle the files and their dependencies into a single javascript file.
Return a readable stream with the javascript file contents oroptionally specify acb(err, buf)
to get the buffered results.
Preventfile
from being loaded into the current bundle, instead referencingfrom another bundle.
Iffile
is an array, each item infile
will be externalized.
Iffile
is another bundle, that bundle's contents will be read and excludedfrom the current bundle as the bundle infile
gets bundled.
Prevent the module name or file atfile
from showing up in the output bundle.
Instead you will get a file withmodule.exports = {}
.
Prevent the module name or file atfile
from showing up in the output bundle.
If your code tries torequire()
that file it will throw unless you've providedanother mechanism for loading it.
Transform source code before parsing it forrequire()
calls with the transformfunction or module nametr
.
Iftr
is a function, it will be called withtr(file)
and it should return athrough-streamthat takes the raw file contents and produces the transformed source.
Iftr
is a string, it should be a module name or file path of atransform modulewith a signature of:
varthrough=require('through');module.exports=function(file){returnthrough()};
You don't need to necessarily use thethrough module, this is just a simpleexample.
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 thecoffeeifymodule:
$ npm install coffeeify$ browserify -t coffeeify main.coffee > bundle.js
Ifopts.global
istrue
, the transform will operate on ALL files, despitewhether they exist up a level in anode_modules/
directory. Use globaltransforms cautiously and sparingly, since most of the time an ordinarytransform will suffice. You can also not configure global transforms in apackage.json
like you can with ordinary transforms.
Global transforms always run after any ordinary transforms have run.
Register aplugin
withopts
. Plugins can be a string module name or afunction the same as transforms.
plugin(b, opts)
is called with the browserify instanceb
.
For more information, consult the plugins section below.
There is an internallabeled-stream-splicerpipeline with these labels:
'record'
- save inputs to play back later on subsequentbundle()
calls'deps'
-module-deps'json'
- addsmodule.exports=
to the beginning of json files'unbom'
- remove byte-order markers'syntax'
- check for syntax errors'sort'
- sort the dependencies for deterministic bundles'dedupe'
- remove duplicate source contents'label'
- apply integer labels to files'emit-deps'
- emit'dep'
event'debug'
- apply source maps'pack'
-browser-pack'wrap'
- apply final wrapping,require=
and a newline and semicolon
You can callb.get()
with a label name to get a handle on a stream pipelinethat you canpush()
,unshift()
, orsplice()
to insert your own transformstreams.
Reset the pipeline back to a normal state. This function is called automaticallywhenbundle()
is called multiple times.
This function triggers a 'reset' event.
browserify uses thepackage.json
in its module resolution algorithm just likenode. If there is a"main"
field, browserify will start resolving the packageat that point. If there is no"main"
field, browserify will look for an"index.js"
file in the module root directory. Here are some moresophisticated things you can do in the package.json:
There is a special "browser" field you canset in your package.json on a per-module basis to override file resolution forbrowser-specific versions of files.
For example, if you want to have a browser-specific module entry point 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 liketransforms it doesn't apply intonode_modules
directories.
You can specify source transforms in the package.json in thebrowserify.transform
field. There is more information about how sourcetransforms work in package.json on themodule-deps readme.
For example, if your module requiresbrfs, youcan add
"browserify": {"transform": ["brfs" ] }
to your package.json. Now when somebodyrequire()
s your module, brfs willautomatically be applied to the files in your module without explicitintervention by the person using your module. Make sure to add transforms toyour package.json dependencies field.
When a file is resolved for the bundle, the bundle emits a'file'
event withthe fullfile
path, theid
string passed torequire()
, and theparent
object used bybrowser-resolve.
You could use thefile
event to implement a file watcher to regenerate bundleswhen files change.
When a package file is read, this event fires with the contents. The packagedirectory is available atpkg.__dirname
.
When.bundle()
is called, this event fires with thebundle
output stream.
When the.reset()
method is called or implicitly called by another call to.bundle()
, this event fires.
When a transform is applied to a file, the'transform'
event fires on thebundle stream with the transform streamtr
and thefile
that the transformis 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 andan 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 aplugin that can factor out common dependencies from multiple entry-points into acommon bundle. Use plugins with-p
and pass options to plugins withsubarg 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, consult thebrowserify-plugin tagon npm.
There is awiki page that lists the known browserifytransforms.
If you write a transform, make sure to add your transform to that wiki page andadd a package.json keyword ofbrowserify-transform
so thatpeople can browse for all the browserifytransforms on npmjs.org.
There is awiki page that lists the known browserifytools.
If you write a tool, make sure to add it to that wiki page andadd a package.json keyword ofbrowserify-tool
so thatpeople can browse for all the browserifytools on npmjs.org.
Writeups for major releases are available indoc/changelog.
Minor and patch releases are documented inchangelog.markdown and on thebrowserify twitter feed.
MIT
About
browser-side require() the node.js way
Resources
License
Uh oh!
There was an error while loading.Please reload this page.