or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-babel--plugin-transform-modules-umd

This plugin transforms ES2015 modules to UMD

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@babel/plugin-transform-modules-umd@7.27.x

To install, run

npx @tessl/cli install tessl/npm-babel--plugin-transform-modules-umd@7.27.0

index.mddocs/

@babel/plugin-transform-modules-umd

@babel/plugin-transform-modules-umd is a Babel plugin that transforms ES2015 module syntax (import/export statements) into Universal Module Definition (UMD) format. UMD enables JavaScript modules to work across different environments including AMD loaders (RequireJS), CommonJS (Node.js), and browser globals with automatic environment detection.

Package Information

  • Package Name: @babel/plugin-transform-modules-umd
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install --save-dev @babel/plugin-transform-modules-umd

Core Imports

// CommonJS - Babel plugin usage
const transformModulesUmd = require("@babel/plugin-transform-modules-umd");
// ESM - TypeScript types only
import type { Options } from "@babel/plugin-transform-modules-umd";
import type { PluginObj, NodePath } from "@babel/core";
import type { Program } from "@babel/types";

Architecture

@babel/plugin-transform-modules-umd works by:

  1. AST Transformation: Analyzes ES2015 import/export statements in the Abstract Syntax Tree
  2. Module Detection: Identifies all module dependencies and exports using @babel/helper-module-transforms
  3. UMD Wrapper Generation: Creates the universal module wrapper that detects the environment
  4. Code Rewriting: Transforms import/export statements into appropriate module system calls
  5. Global Mapping: Maps external dependencies to global variables for browser environments

The plugin integrates with Babel's compilation pipeline and requires Babel 7.0.0 or higher.

Basic Usage

Babel Configuration

Add the plugin to your Babel configuration:

// babel.config.js
module.exports = {
  plugins: ["@babel/plugin-transform-modules-umd"]
};

With options:

// babel.config.js
module.exports = {
  plugins: [
    ["@babel/plugin-transform-modules-umd", {
      globals: {
        "lodash": "_",
        "react": "React"
      },
      exactGlobals: true
    }]
  ]
};

Input/Output Example

Input (ES2015 modules):

import React from "react";
import { map } from "lodash";

export function processData(data) {
  return map(data, item => React.createElement("div", null, item));
}

Output (UMD format):

(function (global, factory) {
  if (typeof define === "function" && define.amd) {
    define(["react", "lodash"], factory);
  } else if (typeof exports !== "undefined") {
    factory(require("react"), require("lodash"));
  } else {
    var mod = { exports: {} };
    factory(global.React, global._);
    global.myModule = mod.exports;
  }
})(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (React, lodash) {
  function processData(data) {
    return lodash.map(data, item => React.createElement("div", null, item));
  }
  
  exports.processData = processData;
});

Capabilities

Plugin Function

The main plugin function that transforms ES2015 modules to UMD format.

/**
 * @babel/plugin-transform-modules-umd plugin function
 * Requires Babel 7.0.0 or higher
 */
declare function plugin(api: PluginAPI, options?: Options): PluginObj;

interface PluginAPI {
  assertVersion(range: number | string): void;
  assumption(name: string): boolean | undefined;
  version: string;
  cache: {
    forever(): boolean;
    never(): boolean;
    using<T>(callback: () => T): T;
    invalidate(reason: string): void;
  };
}

interface PluginObj {
  name: "transform-modules-umd";
  visitor: {
    Program: {
      exit(path: NodePath<Program>, state: any): void;
    };
  };
}

The plugin function is the default export and should be used in Babel configuration files.

Options Interface

Configuration options for customizing the UMD transformation behavior.

interface Options extends PluginOptions {
  /** Allow top-level `this` usage in the transformed module */
  allowTopLevelThis?: boolean;
  
  /** Use exact global variable paths for complex nested globals */
  exactGlobals?: boolean;
  
  /** Mapping of module names to global variable names */
  globals?: Record<string, string>;
  
  /** Import interoperability options for handling different module formats */
  importInterop?: "babel" | "node" | "none";
  
  /** Enable loose mode transformations for smaller output */
  loose?: boolean;
  
  /** Disable interop helpers for simpler output */
  noInterop?: boolean;
  
  /** Enable strict mode in the module wrapper */
  strict?: boolean;
  
  /** Enable strict mode in output (alias for strict) */
  strictMode?: boolean;
}

interface PluginOptions {
  /** Module ID for the transformed module */
  moduleId?: string;
  
  /** Whether to enable module IDs */
  moduleIds?: boolean;
  
  /** Function to generate module ID from module name */
  getModuleId?: (moduleName: string) => string | null | undefined;
  
  /** Root directory for resolving module names */
  moduleRoot?: string;
}

Configuration Options Details

globals

Maps module names to global variable names for browser environments:

{
  "globals": {
    "jquery": "$",
    "lodash": "_",
    "react": "React",
    "react-dom": "ReactDOM"
  }
}

exactGlobals

When true, enables support for nested global paths:

{
  "exactGlobals": true,
  "globals": {
    "my-lib": "MyCompany.Utils.MyLib"
  }
}

This generates code that creates intermediate objects if they don't exist:

global.MyCompany = global.MyCompany || {};
global.MyCompany.Utils = global.MyCompany.Utils || {};
global.MyCompany.Utils.MyLib = mod.exports;

importInterop

Controls how imports are handled for different module systems:

  • "babel" (default): Use Babel's interop helpers for ES6/CommonJS compatibility
  • "node": Use Node.js-style require semantics
  • "none": No interop, direct property access

loose

Enables loose mode for smaller, faster output with some spec compliance trade-offs.

allowTopLevelThis

Allows this to be used at the top level of modules (normally undefined in UMD).

Error Handling

The plugin will throw errors in these cases:

  • Invalid Babel API version: Plugin requires Babel 7.0.0 or higher
  • Invalid configuration options: Malformed options object or invalid option values
  • Malformed ES2015 module syntax: Invalid import/export statements that cannot be transformed
  • Module resolution errors: Issues resolving module dependencies

Common error messages:

  • "Requires Babel \"^7.0.0-0\", but was loaded with \"...\": Babel version mismatch
  • "Unknown option": Invalid configuration option provided
  • AST transformation errors: Thrown during the module rewriting phase when invalid syntax is encountered

Use Cases

  • Library Distribution: Publishing npm packages that work in browsers, Node.js, and AMD environments
  • Legacy Browser Support: Making modern ES2015 modules work in older JavaScript environments
  • Universal Modules: Creating modules that automatically adapt to the available module system
  • Build Tool Integration: Part of build pipelines that need to support multiple deployment targets