browserify vs grunt vs gulp vs parcel vs rollup vs webpack
前端构建工具深度对比:架构选型与工程实践
browserifygruntgulpparcelrollupwebpack

前端构建工具深度对比:架构选型与工程实践

browserify、grunt、gulp、parcel、rollup 和 webpack 代表了前端构建工具演进的不同阶段。browserify 是最早将 CommonJS 模块引入浏览器的工具;grunt 和 gulp 是专注于任务自动化的运行器,前者基于配置,后者基于代码流;webpack 是一个功能强大的模块打包器,通过复杂的依赖图处理各种资源;rollup 专为 ES 模块设计,擅长生成干净的库文件;parcel 则主打零配置和极速开发体验。理解它们的核心机制差异,对于构建高效、可维护的前端架构至关重要。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
browserify014,695363 kB3872 年前MIT
grunt012,23369 kB1583 个月前MIT
gulp032,92111.2 kB311 年前MIT
parcel044,00744 kB6159 个月前MIT
rollup026,3042.95 MB59917 小时前MIT
webpack065,97113.7 MB1175 天前MIT

前端构建工具全景解析:从任务运行器到智能打包器

在前端工程化领域,browserify、grunt、gulp、parcel、rollup 和 webpack 各自解决了不同层面的问题。有些是任务运行器,有些是模块打包器,而有些则是两者的结合。作为架构师,选择工具不仅仅是看流行度,更要看它们如何处理依赖、优化输出以及适应你的开发工作流。让我们深入技术细节,看看它们在实际工程中是如何工作的。

🏗️ 核心定位:任务编排 vs 模块打包

理解这些工具的第一步是区分它们的本质。grunt 和 gulp 是任务运行器,它们不关心你的代码如何模块化,只关心按顺序执行命令。而 webpack、rollup、parcel 和 browserify 是模块打包器,它们的核心工作是分析依赖图,将多个文件合并成一个或多个 bundles。

grunt 基于配置文件。你定义一系列任务,每个任务读取文件、处理、再写回磁盘。这种“读写磁盘”的模式在处理大量文件时效率较低。

// grunt: 基于配置的复杂对象
module.exports = function(grunt) {
  grunt.initConfig({
    uglify: {
      target: {
        files: {
          'dist/app.min.js': ['src/**/*.js']
        }
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-uglify');
};

gulp 基于代码流(Stream)。文件在内存中传递,无需频繁读写磁盘,速度更快,逻辑也更直观。

// gulp: 基于管道的代码流
const { src, dest } = require('gulp');
const uglify = require('gulp-uglify');

function minify() {
  return src('src/**/*.js')
    .pipe(uglify())
    .pipe(dest('dist'));
}

exports.default = minify;

webpack 和 rollup 则关注入口文件,递归分析 import 或 require,将所有依赖打包。webpack 倾向于将所有资源(CSS、图片)都视为模块,而 rollup 更专注于 JavaScript 代码本身的树摇(Tree-shaking)。

// webpack: 入口配置
module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};
// rollup: 简洁的 ES 模块配置
export default {
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'es'
  }
};

⚡ 开发体验:配置复杂度与零配置

在开发阶段,启动速度和配置成本直接影响效率。parcel 以此著称,而 webpack 则以灵活但复杂闻名。

parcel 主打“零配置”。你只需指定入口文件,它自动检测依赖、转换 TypeScript 或 Sass,并开启热更新。无需编写配置文件即可启动项目。

# parcel: 无需配置文件,直接运行
parcel index.html

webpack 需要显式配置 Loader 来处理非 JS 文件。虽然灵活,但初始设置较为繁琐。

// webpack: 必须显式配置 loader 处理 CSS
module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  }
};

rollup 配置介于两者之间。它默认只处理 JS,若需处理其他资源或进行转译,需手动添加插件,但配置结构通常比 webpack 更简单。

// rollup: 手动添加 babel 插件进行转译
import babel from '@rollup/plugin-babel';

export default {
  plugins: [babel({ babelHelpers: 'bundled' })]
};

📦 输出优化:树摇与代码分割

对于生产环境,包体积和加载性能是关键。rollup 在库构建上表现优异,webpack 在应用分割上更强大。

rollup 天生为 ES 模块设计,能极其精准地移除未使用的代码(Tree-shaking),生成的代码结构扁平,非常适合发布 npm 包。

// rollup: 自动移除未使用的 export
// src/math.js
export const add = (a, b) => a + b;
export const sub = (a, b) => a - b; // 如果未被引用,将被移除

// src/index.js
import { add } from './math';
console.log(add(2, 3));
// 输出结果只包含 add 函数

webpack 支持细粒度的动态导入(Dynamic Imports),自动进行代码分割,非常适合大型单页应用的按需加载。

// webpack: 动态导入触发代码分割
button.addEventListener('click', () => {
  import('./heavy-module.js').then(module => {
    module.doSomething();
  });
});
// webpack 会自动将 heavy-module.js 拆分为独立 chunk

grunt 和 gulp 本身不具备模块打包能力,通常需要配合 browserify 或 webpack 使用才能实现代码分割和优化。

// gulp + webpack-stream: 结合使用
const webpack = require('webpack-stream');

function build() {
  return src('src/index.js')
    .pipe(webpack({ /* webpack config */ }))
    .pipe(dest('dist'));
}

browserify 支持基础的打包,但缺乏现代打包器的高级优化功能(如自动代码分割),主要用于将 CommonJS 转换为浏览器可用格式。

// browserify: 基础打包命令
// 将 main.js 及其依赖打包为 bundle.js
browserify src/main.js -o dist/bundle.js

🔌 扩展性与生态系统

当默认功能不足时,插件生态决定了工具的上限。

webpack 拥有最庞大的插件生态。无论是处理 HTML、压缩图片还是分析包体积,都有成熟插件。

// webpack: 使用插件分析包体积
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  plugins: [
    new BundleAnalyzerPlugin()
  ]
};

gulp 的插件生态极其丰富,专注于文件处理任务。你可以轻松找到处理任何文件格式的插件。

// gulp: 使用插件压缩图片
const imagemin = require('gulp-imagemin');

function images() {
  return src('src/images/*')
    .pipe(imagemin())
    .pipe(dest('dist/images'));
}

rollup 插件系统简洁高效,专注于模块转换和优化,社区插件质量高,但数量少于 webpack。

// rollup: 使用插件解析 Node 模块
import nodeResolve from '@rollup/plugin-node-resolve';

export default {
  plugins: [nodeResolve()]
};

parcel 内部集成了许多功能,减少了对外部插件的依赖,但自定义扩展的能力相对较弱。

// parcel: 通过 package.json 简单配置别名
// .parcelrc 或 package.json 中配置,无需复杂插件链
{
  "alias": {
    "react": "preact/compat"
  }
}

🏛️ 架构选型建议

在实际架构决策中,没有银弹,只有最适合场景的工具。

  • 构建大型应用 (SPA):首选 webpack。它的代码分割、热更新和丰富的生态能支撑复杂业务场景。
  • 开发公共库 (Library):首选 rollup。它能产出最干净、体积最小的 ES 模块代码,对 Tree-shaking 支持最好。
  • 快速原型/小型项目:首选 parcel。零配置让你专注于业务逻辑,而非构建细节。
  • 自动化任务流:使用 gulp 配合上述打包器。用 gulp 处理图片、字体等非代码资源的流水线。
  • 遗留系统维护:如果遇到老旧的 CommonJS 项目,browserify 或 grunt 可能是维持现状的唯一选择,但应计划迁移。

📊 核心特性对比总结

特性webpackrollupparcelgulpgruntbrowserify
核心类型模块打包器模块打包器模块打包器任务运行器任务运行器模块打包器
配置方式JS 对象配置JS 对象配置零配置/JSONJS 代码流JSON 配置CLI/JS 配置
主要优势生态最强、功能最全输出代码最干净开发速度最快文件流处理灵活插件配置化CommonJS 兼容
适用场景大型单页应用JS 库/组件库原型/小型项目资源处理流水线旧项目维护旧模块转换
Tree-shaking支持 (需配置)原生极致支持自动支持需配合其他工具需配合其他工具基础支持
代码分割强大 (动态导入)支持 (实验性)自动支持不支持不支持不支持

💡 最终建议

现代前端架构通常是组合式的。我们常见的高效组合是:rollup 用于构建底层组件库,确保体积最小化;webpack 用于构建上层业务应用,利用其强大的分割能力优化加载性能;而 gulp 则作为胶水工具,处理图片优化、文件清理等外围任务。对于新启动的创新型小项目,直接上 parcel 能极大提升迭代速度。避免在新项目中单独使用 grunt 或 browserify,除非有不可逾越的历史包袱。选择工具的本质,是选择一种与你的团队规模和业务复杂度相匹配的工程节奏。

如何选择: browserify vs grunt vs gulp vs parcel vs rollup vs webpack

  • browserify:

    仅当你需要维护极旧的遗留项目,且必须使用 CommonJS (require) 语法而不希望引入复杂构建流程时,才考虑使用 browserify。在现代新项目中,它已被更强大的打包器取代,不建议作为首选方案。

  • grunt:

    如果你的团队严重依赖现成的、配置驱动的旧式插件生态,且不需要复杂的自定义构建逻辑,grunt 仍可勉强使用。但在大多数场景下,其繁琐的配置文件和较慢的执行速度使其不如基于代码流的 gulp 或现代打包器具有竞争力。

  • gulp:

    当你需要编排一系列非打包类的构建任务(如图片压缩、文件重命名、部署脚本)且希望拥有代码级的控制灵活性时,gulp 是最佳选择。它非常适合作为现代打包器(如 webpack 或 rollup)的补充工具,用于处理文件流操作。

  • parcel:

    对于快速原型开发、小型项目或希望彻底摆脱复杂配置文件的团队,parcel 是理想之选。它的零配置特性和内置的热更新能让你立即开始编码,但在需要深度定制构建输出或优化大型应用架构时,其灵活性可能不如 webpack 或 rollup。

  • rollup:

    如果你正在开发 JavaScript 库、UI 组件库或微前端应用,且主要使用 ES 模块 (import/export) 语法,rollup 是行业标准。它能生成体积最小、结构最清晰的打包文件,特别适合需要发布到 npm 的公共库。

  • webpack:

    当构建大型、复杂的企业级单页应用(SPA),需要代码分割、懒加载、丰富的资源加载器(Loader)和庞大的插件生态支持时,webpack 是最稳健的选择。它是目前生态系统最成熟、社区支持最强的通用打包解决方案。

browserify的README

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!