Babel browserify transform that enables modern JavaScript compilation in browserify build processes
npx @tessl/cli install tessl/npm-babelify@10.0.0Babelify is a browserify transform that enables Babel compilation during the browserify build process. It transforms modern JavaScript syntax (ES6+, JSX, TypeScript) into browser-compatible code, serving as a bridge between Babel's powerful transformation capabilities and browserify's module bundling system.
npm install babelify @babel/coreconst babelify = require("babelify");const browserify = require("browserify");
const babelify = require("babelify");
// Direct transform usage
browserify("./script.js")
.transform(babelify, {presets: ["@babel/preset-env", "@babel/preset-react"]})
.bundle()
.pipe(process.stdout);
// Pre-configured transform
browserify("./script.js")
.transform(babelify.configure({
presets: ["@babel/preset-env", "@babel/preset-react"]
}))
.bundle()
.pipe(process.stdout);The main export creates a browserify transform instance that processes files through Babel. Internally uses buildTransform() to create the transform function.
/**
* Creates a browserify transform that processes files through Babel
* @param {string} filename - The file being transformed
* @param {object} transformOpts - Browserify transform options
* @returns {Stream} BabelifyStream or PassThrough stream if file should be skipped
*/
function babelify(filename, transformOpts);
/**
* Internal function that builds the transform with optional preconfigured options
* @param {object} opts - Preconfigured Babel options
* @returns {function} Transform function that accepts (filename, transformOpts)
*/
function buildTransform(opts);Usage Example:
const browserify = require("browserify");
const babelify = require("babelify");
browserify("./src/app.js")
.transform(babelify, {
presets: ["@babel/preset-env"],
plugins: ["@babel/plugin-transform-class-properties"]
})
.bundle()
.pipe(process.stdout);Creates a pre-configured transform function with default options. This is an alias for buildTransform().
/**
* Creates a pre-configured babelify transform with default options
* @param {object} opts - Default Babel options to apply
* @returns {function} Transform function that can be used with browserify
*/
function configure(opts);Note: module.exports.configure is set to buildTransform, so babelify.configure and buildTransform are the same function.
Usage Example:
const browserify = require("browserify");
const babelify = require("babelify");
const myTransform = babelify.configure({
presets: ["@babel/preset-env", "@babel/preset-react"],
sourceMaps: true
});
browserify("./src/app.js")
.transform(myTransform)
.bundle()
.pipe(process.stdout);Custom Symbol.hasInstance property allows instanceof checks with babelify transforms. This enables checking if a stream is created by babelify.
/**
* Custom hasInstance implementation for instanceof checks
* @param {object} obj - Object to check
* @returns {boolean} True if obj is a BabelifyStream instance
*/
babelify[Symbol.hasInstance](obj);This allows you to use instanceof babelify to check if a transform stream was created by babelify, which is useful for handling the 'babelify' event.
Usage Example:
const browserify = require("browserify");
const babelify = require("babelify");
const b = browserify("./src/app.js");
b.transform(babelify, {presets: ["@babel/preset-env"]});
b.on("transform", function(tr) {
if (tr instanceof babelify) {
console.log("This is a babelify transform");
tr.once("babelify", function(result, filename) {
console.log(`Transformed ${filename}`);
console.log(`Result:`, result.code);
});
}
});The transform stream emits a 'babelify' event when transformation completes.
/**
* Event emitted when Babel transformation completes
* @param {object} result - Babel transformation result object
* @param {string} filename - Path of the transformed file
*/
transform.on("babelify", function(result, filename) {});The result object contains:
code - Transformed JavaScript codemap - Source map object (if enabled)ast - Abstract syntax treemetadata - Babel transformation metadataInternal utility functions used in the transformation process:
/**
* Normalizes and merges preconfigured options with transform options
* @param {object} preconfiguredOpts - Options from configure() call
* @param {object} transformOpts - Options from browserify transform
* @param {string} filename - File being transformed
* @returns {object|null} Normalized options or null if file should be skipped
*/
function normalizeOptions(preconfiguredOpts, transformOpts, filename);
/**
* Normalizes the base directory from transform options
* @param {object} opts - Transform options containing _flags.basedir
* @returns {string} Resolved base directory path
*/
function normalizeTransformBasedir(opts);
/**
* Cleans and normalizes transform options, removing browserify-specific properties
* @param {object} opts - Raw transform options
* @returns {object} Cleaned options suitable for Babel
*/
function normalizeTransformOpts(opts);
/**
* Core transformation function that applies Babel to source code
* @param {string} data - Source code to transform
* @param {object} inputOpts - Babel configuration options
* @param {function} done - Callback function (err, result)
*/
function transform(data, inputOpts, done);interface BabelifyOptions {
/** Array of file extensions to transform (default: babel.DEFAULT_EXTENSIONS) */
extensions?: string[];
/** Make source map paths absolute instead of relative */
sourceMapsAbsolute?: boolean;
}The default extensions are determined by Babel's DEFAULT_EXTENSIONS which typically includes [".js", ".jsx", ".es6", ".es", ".mjs"].
Important Behavior:
extensions array are skipped (return PassThrough stream)path.resolve()filename parameter in Babel options is always set to the absolute file pathAll standard Babel configuration options are supported:
interface BabelOptions {
/** Array of Babel presets to apply */
presets?: (string | [string, object])[];
/** Array of Babel plugins to apply */
plugins?: (string | [string, object])[];
/** Source map generation ("inline", true, false) - forced to "inline" for browserify */
sourceMaps?: boolean | "inline";
/** Regex pattern for files to ignore */
ignore?: RegExp;
/** Regex pattern for files to exclusively transform */
only?: RegExp;
/** Working directory for Babel configuration */
cwd?: string;
/** Caller metadata added automatically by babelify */
caller?: object;
/** Filename being transformed (set automatically) */
filename?: string;
/** Source filename for source maps (set automatically) */
sourceFileName?: string;
}Note: Babelify automatically sets caller.name to "babelify" and forces sourceMaps to "inline" when enabled since browserify can only handle inline source maps.
Custom File Extensions:
browserify("./src/app.js")
.transform(babelify, {
extensions: [".babel", ".jsx"],
presets: ["@babel/preset-react"]
});Source Maps:
browserify({debug: true})
.transform(babelify, {
sourceMapsAbsolute: true,
presets: ["@babel/preset-env"]
});File Filtering:
browserify("./src/app.js")
.transform(babelify, {
ignore: /node_modules/,
only: /src\\/.*\\.js$/,
presets: ["@babel/preset-env"]
});Internal transform stream class (extends Node.js Transform stream):
class BabelifyStream extends require("stream").Transform {
/**
* Creates a new BabelifyStream with Babel options
* @param {object} opts - Normalized Babel configuration options
*/
constructor(opts);
/** Internal data buffer for collecting chunks */
_data: Buffer[];
/** Babel options for transformation */
_opts: object;
/**
* Transform method called for each chunk
* @param {Buffer} buf - Data chunk
* @param {string} enc - Encoding
* @param {function} callback - Completion callback
*/
_transform(buf, enc, callback);
/**
* Flush method called when all data has been consumed
* @param {function} callback - Completion callback
*/
_flush(callback);
/** Emitted when transformation completes */
emit(event: "babelify", result: object, filename: string): boolean;
}Babelify will throw specific errors in these scenarios:
The main module exports:
module.exports = buildTransform(); // Main transform function
module.exports.configure = buildTransform; // Alias for buildTransform
module.exports[Symbol.hasInstance] = function hasInstance(obj) {
return obj instanceof BabelifyStream;
};