yarb JavaScript Bundler
yarb (Yet Another Require Bundler) is a JavaScript module bundler designed for the browser environment, serving a similar purpose to Browserify. It focuses on bundling CommonJS-style modules and is currently at version 0.8.0. While its release cadence isn't explicitly stated, the version number suggests a more experimental or niche tool compared to its established alternatives. A key differentiator of yarb is its enhanced capability for defining dependencies between bundles, automatically identifying and excluding common files when using the `external` function, which simplifies multi-bundle setups. However, yarb is less flexible than Browserify, offering limited support for Node.js core modules (only `events`, `fs`, `module`, `net`, `path`, `stream`, `util`) and fewer configuration options. Internally, it utilizes vinyl objects for file representation, allowing for flexible input of buffers or streams, provided they have unique and absolute `path` properties.
Common errors
-
Uncaught ReferenceError: require is not defined
cause Attempting to run a yarb-bundled file in a browser without the necessary CommonJS runtime preamble, or the bundle itself is empty.fixEnsure the bundled output from `bundle.bundle()` is properly included in your HTML, typically within a `<script>` tag. Verify the bundle generation process completed successfully and produced output. -
Error: Cannot find module 'my-module-name'
cause A `require()` call refers to a module that yarb could not locate or include in the bundle. This can happen if the file is not an entry point, not explicitly added via `bundle.add()` or `bundle.require()`, or if the path is incorrect.fixCheck the module path for correctness. If it's not referenced from an entry point, use `bundle.add('./path/to/my-module-name.js')` or `bundle.require('./path/to/my-module-name.js')` to explicitly include it. -
Error: Cannot find module 'http'
cause Attempting to require a Node.js core module that yarb does not support or shim for the browser environment.fixRemove dependencies on unsupported Node.js core modules. For browser-side functionality, find alternative libraries that do not rely on Node.js specifics. -
TypeError: Cannot read properties of undefined (reading 'pipe')
cause This typically occurs when `bundle.bundle()` returns `null` or `undefined`, indicating a configuration error or an unhandled internal error before the stream is created, or when not using a callback.fixInspect previous steps in the bundling chain for errors or misconfigurations. Ensure entry files exist and are correctly specified. Always handle the stream or provide a callback to `bundle.bundle()`.
Warnings
- gotcha yarb only supports a limited set of Node.js core modules: `events`, `fs`, `module`, `net`, `path`, `stream`, `util`. Attempting to require other core modules (e.g., `http`, `crypto`) will result in runtime errors in the browser.
- breaking When providing Vinyl objects as input, each object MUST have a unique and absolute `path` property. These paths are crucial for module resolution and must not conflict or be relative.
- gotcha Transforms, by default, are not applied to code located within `node_modules/` directories. This behavior is designed to prevent unintended modifications to third-party dependencies.
- gotcha When using `bundle.external(externalBundle)`, the `externalBundle` must be loaded on the page *before* any other bundles that reference modules within it. Incorrect loading order will lead to runtime 'module not found' errors.
- gotcha yarb is significantly less flexible and feature-rich than Browserify. It lacks many of Browserify's advanced settings, behaviors, and comprehensive core module shims, making it suitable for simpler bundling tasks.
Install
-
npm install yarb -
yarn add yarb -
pnpm add yarb
Imports
- yarb
import yarb from 'yarb'
const yarb = require('yarb') - yarb
const yarb = require('yarb').yarbconst bundlerInstance = yarb(['./src/entry.js'])
- BundleInstance
const bundle = new yarb.Bundle(['./entry.js'])
const bundle = yarb(['./entry.js'])
Quickstart
const yarb = require('yarb');
const path = require('path');
const fs = require('fs');
// Define a simple custom Browserify-compatible transform
function myTransform(file) {
let data = '';
const stream = require('stream');
const tr = new stream.Transform();
tr._transform = function (chunk, encoding, callback) {
data += chunk.toString();
callback();
};
tr._flush = function (callback) {
this.push(Buffer.from(data.replace(/foo/g, 'bar')));
callback();
};
return tr;
}
const mainDirPath = path.join(__dirname, 'yarb-src');
const mainFilePath = path.join(mainDirPath, 'main.js');
const utilFilePath = path.join(mainDirPath, 'utils', 'helper.js');
const outputFilePath = path.join(__dirname, 'yarb-bundle.js');
// Create dummy files for demonstration
fs.mkdirSync(path.dirname(utilFilePath), { recursive: true });
fs.writeFileSync(mainFilePath, "console.log(require('./utils/helper').greet('World') + ' foo');");
fs.writeFileSync(utilFilePath, "exports.greet = (name) => `Hello, ${name}!`;");
const bundle = yarb([mainFilePath], { debug: true }) // Enable source maps
.add(utilFilePath) // Add utility file explicitly if not directly required
.transform(myTransform); // Apply the custom transform
bundle.bundle((err, buf) => {
if (err) {
console.error('Bundling failed:', err);
return;
}
console.log('Bundle created successfully. Writing to', outputFilePath);
fs.writeFileSync(outputFilePath, buf.toString());
console.log('--- Bundled Output (truncated) ---\n' + buf.toString().substring(0, 500));
// Clean up dummy files
fs.unlinkSync(mainFilePath);
fs.unlinkSync(utilFilePath);
fs.rmdirSync(path.dirname(utilFilePath));
fs.rmdirSync(mainDirPath);
console.log('\nDummy files cleaned up.');
});