browser-side require() the node.js way

Overview

browserify

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.

build status

browserify!

getting started

If you're new to browserify, check out the browserify handbook and the resources on browserify.org.

example

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!

install

With npm do:

npm install browserify

usage

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.

  --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.

  --no-browser-field, --no-bf

    Turn off package.json browser field resolution. This is also handy if you
    need to run a bundle in node.

  --transform-key

    Instead of the default package.json#browserify#transform field to list
    all transforms to apply when running browserify, a custom field, like, e.g.
    package.json#browserify#production or package.json#browserify#staging
    can be used, by for example running:
    * `browserify index.js --transform-key=production > bundle.js`
    * `browserify index.js --transform-key=staging > bundle.js`

  --node

    Alias for --bare and --no-browser-field.

  --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.

  --no-dedupe

    Turn off deduping.

  --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.

  --ignore-transform=MODULE, -it MODULE

    Do not run certain transformations, even if specified elsewhere.

  --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 })

compatibility

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:

  • process
  • Buffer
  • global - top-level scope object (window)
  • __filename - file path of the currently executing file
  • __dirname - directory path of the currently executing file

more examples

external requires

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>

external source maps

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.

multiple bundles

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.

api example

You can use the API directly too:

var browserify = require('browserify');
var b = browserify();
b.add('./browser/main.js');
b.bundle().pipe(process.stdout);

methods

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

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.

b.add(file, opts)

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.

b.require(file, opts)

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 can also be a stream, but you should also use opts.basedir so that relative requires will be resolvable.

If file is an array, each item in file will be required. In file array form, you can use a string or object for each item. Object items should have a file property and the rest of the parameters will be used for the opts.

Use the expose property of opts to specify a custom dependency name. require('./vendor/angular/angular.js', {expose: 'angular'}) enables require('angular')

b.bundle(cb)

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, buf) to get the buffered results.

b.external(file)

Prevent file from being loaded into the current bundle, instead referencing from another bundle.

If file is an array, each item in file will be externalized.

If file is another bundle, that bundle's contents will be read and excluded from the current bundle as the bundle in file gets bundled.

b.ignore(file)

Prevent the module name or file at file from showing up in the output bundle.

If file is an array, each item in file will be ignored.

Instead you will get a file with module.exports = {}.

b.exclude(file)

Prevent the module name or file at file from showing up in the output bundle.

If file is an array, each item in file will be excluded.

If your code tries to require() that file it will throw unless you've provided another mechanism for loading it.

b.transform(tr, opts={})

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. Browserify is compatible with the newer, more verbose Transform streams built into Node v0.10.

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.

Transforms may obtain options from the command-line with subarg syntax:

$ browserify -t [ foo --bar=555 ] main.js

or from the api:

b.transform('foo', { bar: 555 })

In both cases, these options are provided as the second argument to the transform function:

module.exports = function (file, opts) { /* opts.bar === 555 */ }

Options sent to the browserify constructor are also provided under opts._flags. These browserify options are sometimes required if your transform needs to do something different when browserify is run in debug mode, for example.

b.plugin(plugin, opts)

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.

b.pipeline

There is an internal labeled-stream-splicer pipeline with these labels:

  • 'record' - save inputs to play back later on subsequent bundle() calls
  • 'deps' - module-deps
  • 'json' - adds module.exports= to the beginning of json files
  • 'unbom' - remove byte-order markers
  • 'unshebang' - remove #! labels on the first line
  • '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 call b.pipeline.get() with a label name to get a handle on a stream pipeline that you can push(), unshift(), or splice() to insert your own transform streams.

b.reset(opts)

Reset the pipeline back to a normal state. This function is called automatically when bundle() is called multiple times.

This function triggers a 'reset' event.

package.json

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:

browser field

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 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 like transforms, it doesn't apply into node_modules directories.

browserify.transform

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.

events

b.on('file', function (file, id, parent) {})

b.pipeline.on('file', function (file, id, parent) {})

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.

b.on('package', function (pkg) {})

b.pipeline.on('package', function (pkg) {})

When a package file is read, this event fires with the contents. The package directory is available at pkg.__dirname.

b.on('bundle', function (bundle) {})

When .bundle() is called, this event fires with the bundle output stream.

b.on('reset', function () {})

When the .reset() method is called or implicitly called by another call to .bundle(), this event fires.

b.on('transform', function (tr, file) {})

b.pipeline.on('transform', function (tr, file) {})

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.

plugins

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, consult the browserify-plugin tag on npm.

list of source transforms

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.

third-party tools

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.

changelog

Releases are documented in changelog.markdown and on the browserify twitter feed.

license

MIT

browserify!

Comments
  • Replace JSONStream with jsonstream

    Replace JSONStream with jsonstream

    NPM now has opinions about names of modules when publishing. We have an internal NPM registry and cannot sync browserify to is due to this dependency. No fear, @dominictarr has published a lowercase version.

    • [x] browser-pack https://github.com/substack/browser-pack/pull/57
    • [x] deps-sort https://github.com/substack/deps-sort/pull/5
    • [x] insert-module-globals https://github.com/substack/insert-module-globals/pull/44
    • [x] module-deps https://github.com/substack/module-deps/pull/84
    opened by chadhietala 48
  • Allow transforms to be configured with options

    Allow transforms to be configured with options

    I've been messing around with my own transforms and see a lot of potential for them to replace certain grunt tasks I have, but I'd need to be able to pass them additional options.

    I originally tweeted something along the lines of this on twitter and @substack replied saying currently the best way is using environment variables: https://twitter.com/substack/statuses/410566575117185024

    I imagine them too look something like this:

    browserify: {
      transforms: [
        "coffeeify",
        {name: "ngtemplateify", module: "mod"}
      ]
    }
    

    Also regarding transforms, perhaps it would be good to be able to turn off module level transforms from these options, for example, lets say I'm using some special transforms that are in my karma config:

    browserify: {
      transforms: [
        {name: "coffeeify", disable: true},
        // not a published transform yet, but would use Ibrik to add 
        // coverage and at the same time convert coffee files to javascript
        {name: "ibrikify"} 
      ]
    }
    

    In that case, if I had a module level transform specifying "coffeeify", my "ibrikify" transform would already have converted the coffee files to js and when the module level transform was applied it would throw an error. So, this would solve that problem without having to expose something like transformKey as a browserify option to be able to set it to false ignoring all module level transforms.

    opened by colinkahn 47
  • relative require throws

    relative require throws "can only load non-root modules"

    With the removal of the base option from browserify, I am trying to update my project to utilise the require option instead.

    Given the following structure...

    /
        /modules
            entry.coffee
            /a
                a.coffee
            /b
                b.coffee
    

    If entry requires ./a/a and a requires ../b/b then the following is thrown on requiring entry

    Can only load non-root modules in a node_modules directory for file: /Users/pyrotechnick/webclient/modules/b/b.coffee
    

    Similarly, when modules/b is nested within modules/a it throws the same error.

    opened by pyrotechnick 43
  • transformers require using extension in require() invocations

    transformers require using extension in require() invocations

    This is awful.

    I enjoy having the freedom of writing in CoffeeScript or JavaScript, and making use of the require() hack in node to load .coffee files automagically. Or, if I want, compile to JS. Code works either way.

    If I want to use transformers, now I need to reference CoffeeScript modules with a ".coffee" extension in the require() parameter, which means compiling to JS won't work anymore.

    Seems like what needs to happen is:

    • transformers should indicate extensions they consider valid module source
    • those extensions should be taken into account when resolving modules
    opened by pmuellr 37
  • Version 8.0.2 broke my build with gulp

    Version 8.0.2 broke my build with gulp

    Not sure weather this is a browserify issue, but versions prior to 8.0.2 used to work fine (including 8.0.1).

    Now it exits with this error:

    Error: write after end
        at writeAfterEnd (D:\code\webgis\node_modules\browserify\node_modules\labeled-stream-splicer\node_modules\stream-spl
    icer\node_modules\readable-stream\lib\_stream_writable.js:161:12)
    

    Here is my build code:

    var browserify = require('browserify');
    var rename = require('gulp-rename');
    var transform = require('vinyl-transform');
    var reactify = require('reactify');
    var size = require('gulp-size');
    gulp.task('scripts-debug', function () {
        var browserified = transform(function (filename) {
            var b = browserify(filename, {
                debug: true,
                extensions: ['.js', '.jsx']
            });
            b.transform(reactify);
            return b.bundle();
        });
    
        gulp.src('src/js/app.js')
            .pipe(browserified)
            .pipe(rename('bundle.js'))
            .pipe(gulp.dest('build/js'))
            .pipe(size({ showFiles: true }));
    });
    
    opened by burmisov 36
  • Source maps not working with Firefox

    Source maps not working with Firefox

    Firefox has partial support for source maps. The Console tab doesn't use them yet, but ClojureScript's source maps are working fine for me in the Debugger tab. Browserify's do not.

    The issue seems to be full pathnames in the source map's "sources" key:

        "sources": [
            "/home/graue/code/projectname/node_modules/browserify/node_modules/browser-pack/_prelude.js",
            "/home/graue/code/projectname/node_modules/backbone/backbone.js",
            "/home/graue/code/projectname/node_modules/bean/bean.js",
            "/home/graue/code/projectname/node_modules/browserify/node_modules/buffer/index.js",
            "/home/graue/code/projectname/node_modules/browserify/node_modules/buffer/node_modules/base64-js/lib/b64.js",
            "/home/graue/code/projectname/node_modules/browserify/node_modules/buffer/node_modules/ieee754/index.js",
            ...
        ]
    

    If I remove the beginnings of each path so all the pathnames are relative to the project root, e.g.

            "node_modules/browserify/node_modules/browser-pack/_prelude.js",
            "node_modules/backbone/backbone.js",
    

    then base64-encode the modified source map and stick it back into the Browserify bundle, Firefox's debugger is happy (and Chrome's still is, too).

    I've done this manually but may be able to work on a PR for this later, if making Browserify use relative paths is seen as an acceptable change and the best way to go here. Let me know if that sounds like a good plan.

    support 
    opened by graue 35
  • Pass extensions opts key to module-deps and browser-resolve calls

    Pass extensions opts key to module-deps and browser-resolve calls

    This is due #326 — to allow requiring non-js files w/o extensions while using browserify.

    This pull request depends on shtylman/node-browser-resolve#12 and substack/module-deps#5 and doesn't have tests while I'll add some if you are willing to accepts such functionality. Please note that I don't want this pull request to be merged, this is just to describe an idea and provide a use-case for pull requests mentioned above — API implemented now is quite verbose and dirty.

    Basically it allows to specify which file extensions modules can have, so instead of considering only .js files it could be configured to to look for .coffee files for example:

    browserify --extension '.coffee' --extension '.mustache' ...
    

    So you can write simply require('module') for requiring module.coffee.

    I think that CoffeeScript (actually same goes for TypeScript and Roy and others langs compiled to js) community can benefit a lot from this because it is natural to think of coffeescript modules as interchangeable with "native" javascript modules — even Node allows loading coffee modules via require.extensions registry.

    opened by andreypopp 35
  • Support for asynchronous loading (and not packing everything in one file)

    Support for asynchronous loading (and not packing everything in one file)

    Packing everying in one file causes some problems:

    • You have to re-pack the whole thing everytime you modify a single file
    • When an error is reported during execution, it does not reports the line number and file name of the real source file
    • Multiple browserified modules can't share dependencies: they are packed independently in each module; as a result they are downloaded twice.

    This is a feature request to add support (as a browserify option) for using asynchronous loading instead of packing everything in a single file.

    This would solve all the problems described above: dev becomes easier, bandwidth is saved, and pages load faster (because scripts are loaded asynchronously).

    Most node modules are currently using synchronous loading, but it would be possible to convert a script like that:

    var http = require('http');
    
    function doRequest() {
        var url = require('url');
        ....
    }
    
    exports.doRequest = doRequest;
    

    To something like this:

    define(['http', 'url'], function(http, url) {
        function doRequest() {
            ....
        }
    
        exports.doRequest = doRequest;
        return exports;
    });
    

    Or even easier (just wrap the unmodified script with a header and footer):

    define(['http', 'url'], function() {
    
        // now that http and url modules are loaded, require('http') and require('url') can be used directly
        // no need to modify the script :-)
    
        var http = require('http');
    
        function doRequest() {
            var url = require('url');
            ....
        }
    
        exports.doRequest = doRequest;
        return exports;
    });
    

    Optimization

    Such asynchronous modules can still be packed together in a single javascript file for reducing the number of HTTP requests in production.

    This is done by just adding the module name as first argument of define (define('moduleName', ['dependency'], func)) and concatenating all modules.

    opened by arnaud-lb 33
  • Error: EMFILE on OSX when requiring lots of files

    Error: EMFILE on OSX when requiring lots of files

    When requiring 256 files from a single file on OSX browserify throws:

    Error: EMFILE, open '/Users/karl/Sites/KVP/GuruFramework/package.json'
    

    From Googling around it looks like this is caused by attempting to open too many files in parallel.

    It looks like this could be solved by using the graceful-fs module to limit the number of files opened in parallel.

    https://github.com/isaacs/node-graceful-fs

    opened by karl 32
  • browserify dedupe doesn't play well with source maps

    browserify dedupe doesn't play well with source maps

    @johnkpaul ran into an issue as follows:

    When bundling a file, lets call it foo.js, with the same content twice, it is deduped and one just has a redirecting require in it, i.e.:

    module.exports = require('some id here');
    

    Unfortunately the content for foo.js included in the source maps is not the original content, but the one line redirect instead.

    As a result it is impossible to debug the actual code of foo.js since opening it up in dev tools just shows the one line redirect instead of the original foo.js content.

    I'm yet unclear on what exactly is going on, since both file still should have gotten different ids and therefore the sourcemaps should contain multiple foo.jss each with different paths. So we need to investigate further.

    Possibly @johnkpaul can provide an isolated test case, otherwise I'll try to repro it.

    I'm not sure how this can be fixed, but have three general options how to approach it:

    • a) When generating the row, indicate if it just contains a redirect to another file, i.e. row.redirect = true. The sourcemap generation in browser-pack can then take that into account.
    • b) The sourcemap generation in browser-pack gets smart enough to realize that if we already generated a sourcemap for a file content and the current content is shorter, it is most likely a redirect and should not overwrite the original content.
    • c) The sourcemap generation in browser-pack assumes that rows are ordered so that redirects are emitted after the original content. Therefore it will just check in the hash if it already generated sourcemaps for the file and doesn't overwrite it.
    opened by thlorenz 30
  • Expose property doesn't work when requiring a module name

    Expose property doesn't work when requiring a module name

    With the latest version (5.9.1), aliasing a module name doesn't work anymore. browserify -r fs:browserify-fs doesn't create the alias. With an older version (4.2.3), an alias was created with the same command.

    No issue with specifying a file instead of a module name.

    opened by tleunen 29
  • Why can't browserify find this npm module?

    Why can't browserify find this npm module?

    Hello, sorry if this is the wrong place to ask, but I'm tearing my hair out over this. For the life of me, browserify won't acknowledge an installed module:

    % npm install -g browserify
    % . ~/.bash_profile
    % npm install --save ipfs-http-client
    % browserify main.js        
    Error: Can't walk dependency graph: Cannot find module 'ipfs-http-client' from '/Users/disco/Programming/DiscoChat/browserify-sadness/main.js'
        required by /Users/disco/Programming/DiscoChat/browserify-sadness/main.js
        at /opt/homebrew/lib/node_modules/browserify/node_modules/resolve/lib/async.js:146:35
        at processDirs (/opt/homebrew/lib/node_modules/browserify/node_modules/resolve/lib/async.js:299:39)
        at isdir (/opt/homebrew/lib/node_modules/browserify/node_modules/resolve/lib/async.js:306:32)
        at /opt/homebrew/lib/node_modules/browserify/node_modules/resolve/lib/async.js:34:69
        at FSReqCallback.oncomplete (node:fs:211:21)
    

    main.js

    var IpfsHttpClient = require('ipfs-http-client');
    
    async function onload() {
    	ipfs = await IpfsHttpClient.create({url: "http://127.0.0.1:5001", timeout: "5m"});
    
    	// try to get our peerid
    	try {	
    		me = await ipfs.id();
    	} catch { // if we fail, try again in 1 second
    		setTimeout(function(){onload()}, 1000);
    		return;
    	}
    
    	document.getElementById("status").innerHTML = "Kubo node is running, PeerID: " + me.id.toString();
    }
    

    The example in the README works fine, but if I follow the exact same steps with ipfs-http-client it can't even find it.

    opened by TheDiscordian 1
  • Using the new Function class in the output JS

    Using the new Function class in the output JS

    Hello everyone! I'm not too experienced with browserify, however I've recently been having a problem with the Chrome extensions manifest v3 which will take over manifest v2 in early 2023.

    The problem is that browserify outputs the bundle with calls using the "new Function" class in javascript and that's no longer allowed with manifest v3. This could potentially mean that no one could use browserify when developing chrome extensions from what I can see.

    nsfwJS uses browserify and that is used in a few chrome extensions to help remove or blur NSFW content, Here's the issue.

    Could anyone help us out here? The goal would be to avoid using eval, new Function, or any other way of executing strings. Thanks!

    opened by Acorn221 1
  • Why dose Browserfy fails to parse for normal JavaScript Class fields declaration?

    Why dose Browserfy fails to parse for normal JavaScript Class fields declaration?

    I mentioned the detail here https://stackoverflow.com/questions/71910376/why-dose-browserfy-fails-to-parse-for-normal-javascript-class-fields-declaration

    Thanks

    opened by 3DGISKing 0
  • "ReactifyError: PATH: Parse Error: Line 11: Illegal rment while parsing file: FILE" error

    When i to use command "browserify loginsystem.js > info.js" i got error:

    ReactifyError: C:\Users\User\Documents\HAIKAL\Proyek\Si Reina\converter test\voi
    ce subtitle test\loginsystem.js: Parse Error: Line 11: Illegal return statement
    while parsing file: C:\Users\User\Documents\HAIKAL\Proyek\Si Reina\converter tes
    t\voice subtitle test\loginsystem.js 
    

    How to fix that error?

    opened by justClizz 1
  • Inconsistent output file between windows and ubuntu

    Inconsistent output file between windows and ubuntu

    Hi there, I'm trying to bundle same code on windows and ubuntu, and use gulp-uglify to compress the output files. Most of the output files are identical (with the same checksum) but only one is different. Don't know if browserify has any guarantees for this kind of cross-platform consistency, but it might be an issue worth looking into.

    Below is a minimal POC that I've found by constantly trying. My project relies on echarts@^4.2.1, and uses gulp to run browserify to generate the bundle and finally compress it through gulp-uglify. In most cases this process will produce the same files on different platforms (at least in my current project).

    browserify-gulp-example.zip

    The output is the same on Ubuntu and macOS, but not on Windows. The difference is only some digital labels (causing inconsistent order of modules): ScreenShot 2022-03-23 171347

    From what I've tried, echarts/lib/component/axis/AxisView is causing this inconsistency. However, if I add bundle.require('echarts/lib/component/axis/AxisView'); after line 10 of gulpfile.js, the output becomes consistent.

    Below is the content of gulpfile.js. All files are available in zip archives.

    const gulp = require('gulp');
    const browserify = require('browserify');
    const source = require('vinyl-source-stream');
    const uglify = require('gulp-uglify');
    const rev = require('gulp-rev');
    
    function buildMain() {
        let bundle = browserify({
            entries: './main.js',
        });
        // uncomment next line the output will be consistent.
        // bundle.require('echarts/lib/component/axis/AxisView');
        return bundle.bundle()
            .pipe(source('main.js'))
            .pipe(gulp.dest('./bundle'));
    }
    
    gulp.task('build', gulp.series(buildMain, (done) => {
        return gulp.src(`./bundle/*.js`)
            .pipe(uglify())
            .pipe(rev())
            .pipe(gulp.dest(`./dist/scripts`))
            .pipe(rev.manifest())
            .pipe(gulp.dest('./bundle'));
    }));
    

    main.js has only one line:

    require('echarts/lib/component/axis/AxisView');
    

    Environment:

    • Node version: 16.14.2 on all platforms, installed via nvm and nvm-windows.
    • OS version: Windows 11, Ubuntu 20.04 and macOS 12.3.
    • npm version: 8.5.5 on all platforms.
    opened by scp-r 1
Releases(v17.0.0)
  • v17.0.0(Oct 10, 2020)

    • Upgrade events to v3.x. EventEmitter instances now have an off() method. require('events').once can be used to react to an event being emitted with async/await syntax. (#1839)
    • Upgrade path-browserify to v1.x. (#1838)
    • Upgrade stream-browserify to v3.x. require('stream') now matches the Node.js 10+ API. (#1970)
    • Upgrade util to v0.12. Most notably, util.promisify and util.callbackify are finally available by default in browserify. (#1844)
    • Add JSON syntax checking. Syntax errors in .json files will now fail to bundle. (#1700)
    Source code(tar.gz)
    Source code(zip)
  • v16.5.1(Mar 30, 2020)

    Remove deprecated mkdirp version in favour of mkdirp-classic.

    https://github.com/browserify/browserify/commit/00c913fa345dbb7f612bdad6b4acc91c706e98b2

    Pin dependencies for Node.js 0.8 support.

    https://github.com/browserify/browserify/pull/1939

    Source code(tar.gz)
    Source code(zip)
  • v16.5.0(Aug 25, 2019)

    Support custom name for "browser" field resolution in package.json using the browserField option.

    https://github.com/browserify/browserify/pull/1918

    Source code(tar.gz)
    Source code(zip)
  • v16.4.0(Aug 25, 2019)

  • v16.3.0(Jul 11, 2019)

    add empty stub for the http2 builtin module.

    https://github.com/browserify/browserify/pull/1913

    update license text to remove references to code that is no longer included.

    https://github.com/browserify/browserify/pull/1906

    add more tests for folder resolution.

    https://github.com/browserify/browserify/pull/1139

    Source code(tar.gz)
    Source code(zip)
  • v16.2.3(Sep 25, 2018)

    add empty stub for the inspector builtin module.

    https://github.com/browserify/browserify/pull/1854

    change the "browser" field link to the browser-field-spec repo instead of the old gist.

    https://github.com/browserify/browserify/pull/1845

    Source code(tar.gz)
    Source code(zip)
  • v16.2.2(May 9, 2018)

  • v16.2.1(May 9, 2018)

    Fix relative --external paths on Windows. (@Shingyx)

    https://github.com/browserify/browserify/pull/1704

    Fix tests to work on Windows, and add Appveyor CI for Windows testing.

    https://github.com/browserify/browserify/pull/1819

    Source code(tar.gz)
    Source code(zip)
  • v16.2.0(Apr 11, 2018)

    update the browser versions of vm-browserify and string_decoder.

    string_decoder updates to the Node 8+ API. vm-browserify replaces an unlicensed dependency by an MIT one.

    https://github.com/browserify/browserify/pull/1829

    Source code(tar.gz)
    Source code(zip)
  • v16.1.1(Apr 11, 2018)

  • v16.1.0(Apr 11, 2018)

  • v16.0.0(Apr 11, 2018)

    add --preserve-symlinks option from Node 6.3

    https://github.com/browserify/browserify/pull/1742 https://github.com/browserify/browserify/pull/1801

    update the browser version of events to 2.0.0—this version adds methods like prependListener that were introduced in recent node versions, but it is also twice the size of events v1.x (2KB instead of 1KB).

    https://github.com/browserify/browserify/pull/1803

    Dynamically calculate __dirname and __filename when --node is passed

    https://github.com/browserify/browserify/pull/1725

    upgrade module-deps, see https://github.com/browserify/module-deps/releases/tag/v6.0.0

    https://github.com/browserify/browserify/commit/e5e1ec8799f1007a56118ae46646e0048385ed84

    Source code(tar.gz)
    Source code(zip)
  • v15.1.0(Jan 11, 2018)

  • 13.0.1(May 6, 2016)

Package your Node.js project into an executable

Disclaimer: pkg was created for use within containers and is not intended for use in serverless environments. For those using Vercel, this means that

Vercel 22.6k Jan 7, 2023
A powerful and lightweight inversion of control container for JavaScript & Node.js apps powered by TypeScript.

InversifyJS A powerful and lightweight inversion of control container for JavaScript & Node.js apps powered by TypeScript. About InversifyJS is a ligh

inversify 9.5k Jan 4, 2023
:red_circle: Functional task runner for Node.js

start ⚠️ Project has been transferred to NexTools metarepo functional – in all senses fast – parallelism and concurrency shareable – presets as publis

Kir Belevich 477 Dec 15, 2022
Build node packages into deployable applications

strong-build Build a node application package, preparing it for deploy to production. It is useful standalone, but is commonly used to build applicati

StrongLoop and IBM API Connect 47 Mar 3, 2022
browser-side require() the node.js way

browserify require('modules') in the browser Use a node-style require() to organize your browser code and load modules installed by npm. browserify wi

null 14.3k Dec 31, 2022
browser-side require() the node.js way

browserify require('modules') in the browser Use a node-style require() to organize your browser code and load modules installed by npm. browserify wi

null 14.3k Dec 29, 2022
⚡️The Fullstack React Framework — built on Next.js

The Fullstack React Framework "Zero-API" Data Layer — Built on Next.js — Inspired by Ruby on Rails Read the Documentation “Zero-API” data layer lets y

⚡️Blitz 12.5k Jan 4, 2023
This is an application that entered the market with a mobile application in real life. We wrote the backend side with node.js and the mobile side with flutter.

HAUSE TAXI API Get Started Must be installed on your computer Git Node Firebase Database Config You should read this easy documentation Firebase-Fires

Muhammet Çokyaman 4 Nov 4, 2021
LoopBack makes it easy to build modern API applications that require complex integrations.

LoopBack makes it easy to build modern applications that require complex integrations. Fast, small, powerful, extensible core Generate real APIs with

StrongLoop and IBM API Connect 4.4k Jan 6, 2023
🔮 Proxies nodejs require in order to allow overriding dependencies during testing.

proxyquire Proxies nodejs's require in order to make overriding dependencies during testing easy while staying totally unobtrusive. If you want to stu

Thorsten Lorenz 2.7k Dec 27, 2022
LoopBack makes it easy to build modern API applications that require complex integrations.

LoopBack makes it easy to build modern applications that require complex integrations. Fast, small, powerful, extensible core Generate real APIs with

StrongLoop and IBM API Connect 4.4k Jan 4, 2023
A demo of using the new require.context syntax in Expo with Metro bundler

Metro Context Modules Demo This is a demo of using the experimental 'Context Module' (require.context) feature in Metro bundler. Setup metro.config.js

Evan Bacon 17 Nov 19, 2022
Shikhar 4 Oct 9, 2022
Talk to anyone connected to your network, be it LAN or your hotspot. Doesn't require internet.

Apophis CLI to talk to anyone connected to your network, be it LAN or your hotspot. Doesn't require internet. Installation Make sure you have NodeJS (

Saurav Pal 3 Oct 16, 2022
Make drag-and-drop easier using DropPoint. Drag content without having to open side-by-side windows

Make drag-and-drop easier using DropPoint! DropPoint helps you drag content without having to open side-by-side windows Works on Windows, Linux and Ma

Sudev Suresh Sreedevi 391 Dec 29, 2022
Fast and minimal JS server-side writer and client-side manager.

unihead Fast and minimal JS <head> server-side writer and client-side manager. Nearly every SSR framework out there relies on server-side components t

Jonas Galvez 24 Sep 4, 2022
This plugin allows side-by-side notetaking with videos. Annotate your notes with timestamps to directly control the video and remember where each note comes from.

Obsidian Timestamp Notes Use Case Hello Obsidian users! Like all of you, I love using Obsidian for taking notes. My usual workflow is a video in my br

null 74 Jan 2, 2023
Easy server-side and client-side validation for FormData, URLSearchParams and JSON data in your Fresh app 🍋

Fresh Validation ??     Easily validate FormData, URLSearchParams and JSON data in your Fresh app server-side or client-side! Validation Fresh Validat

Steven Yung 20 Dec 23, 2022
This Plugin is For Logseq. If you're using wide monitors, you can place journals, linked references, and journal queries side by side.

Logseq Column-Layout Plugin Journals, linked references, and journal queries can be placed side by side if the minimum screen width is "1850px" or mor

YU 14 Dec 14, 2022
A server side agnostic way to stream JavaScript.

JS in JSN A server side agnostic way to stream JavaScript, ideal for: inline hydration network free ad-hoc dependencies bootstrap on demand libraries

Andrea Giammarchi 26 Nov 21, 2022