CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-babelify

Babel browserify transform that enables modern JavaScript compilation in browserify build processes

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

Babelify

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

Package Information

  • Package Name: babelify
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install babelify @babel/core

Core Imports

const babelify = require("babelify");

Basic Usage

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

Capabilities

Transform Function

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

Configure Method

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

Instance Checking

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

Babelify Event

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 code
  • map - Source map object (if enabled)
  • ast - Abstract syntax tree
  • metadata - Babel transformation metadata

Internal Transform Process

Internal 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);

Configuration Options

Babelify-Specific Options

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:

  • Files with extensions not in the extensions array are skipped (return PassThrough stream)
  • File paths are automatically resolved to absolute paths using path.resolve()
  • The filename parameter in Babel options is always set to the absolute file path
  • Buffer chunks are concatenated before transformation to avoid corrupting multibyte characters

Standard Babel Options

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

Usage Examples

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"]
  });

Types

BabelifyStream

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

Error Handling

Babelify will throw specific errors in these scenarios:

  • Missing @babel/core: If @babel/core is not installed, throws MODULE_NOT_FOUND with helpful message
  • Incompatible Babel version: If @babel/core@6.x bridge package is detected, throws version incompatibility error
  • Babel transformation errors: Passes through Babel transformation errors (syntax errors, plugin errors, etc.)

Module Structure

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

Dependencies

  • @babel/core: Required peer dependency (^7.0.0) - loaded dynamically with helpful error messages
  • stream: Node.js built-in module (Transform stream base class)
  • util: Node.js built-in module (utility functions)
  • path: Node.js built-in module (file path operations)

Compatibility

  • Node.js: >=6.9.0
  • Babel: 7.x only (requires @babel/core)
  • Browserify: Compatible with standard browserify transform API

docs

index.md

tile.json