or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

babel-plugin-minify-mangle-names

babel-plugin-minify-mangle-names is a Babel plugin that performs context-aware and scope-aware variable renaming for JavaScript minification. It intelligently mangles variable names to shorter identifiers while preserving semantic correctness by respecting scope boundaries, avoiding naming conflicts, and handling edge cases.

Package Information

  • Package Name: babel-plugin-minify-mangle-names
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install babel-plugin-minify-mangle-names --save-dev

Core Imports

The plugin is used through Babel configuration rather than direct imports in your code.

Basic Usage

Via .babelrc (Recommended)

{
  "plugins": ["minify-mangle-names"]
}

With options:

{
  "plugins": [
    ["minify-mangle-names", { 
      "exclude": { "jQuery": true, "$": true },
      "keepFnName": false,
      "keepClassName": false,
      "topLevel": false,
      "eval": false
    }]
  ]
}

Via CLI

babel --plugins minify-mangle-names script.js

Via Node API

const babel = require("@babel/core");

const result = babel.transformSync(sourceCode, {
  plugins: [
    ["minify-mangle-names", {
      exclude: { "globalVar": true },
      keepFnName: true
    }]
  ]
});

console.log(result.code); // Transformed code with mangled variable names

Transformation Example

Input:

var globalVariableName = 42;
function foo() {
  var longLocalVariableName = 1;
  if (longLocalVariableName) {
    console.log(longLocalVariableName);
  }
}

Output:

var globalVariableName = 42;
function foo() {
  var a = 1;
  if (a) {
    console.log(a);
  }
}

Capabilities

Plugin Configuration

The plugin is configured through Babel's plugin options system.

/**
 * Babel plugin factory function exported as module.exports
 * @param {Object} babel - Babel instance with types and traverse utilities
 * @param {Object} babel.types - Babel types utilities
 * @param {Function} babel.traverse - Babel traverse function
 * @returns {Object} Plugin configuration object with name and visitor
 */
module.exports = function(babel) {
  return {
    name: "minify-mangle-names",
    visitor: {
      Program: {
        exit(path) {
          // Plugin implementation with character frequency analysis
          // and intelligent variable name mangling
        }
      }
    }
  };
};

Plugin Options

Configure the mangling behavior through plugin options.

/**
 * Plugin options for configuring mangling behavior
 * @typedef {Object} PluginOptions
 * @property {Object.<string, boolean>|Array<string>} [exclude={}] - Either an object with keys as identifier names and boolean values indicating whether to exclude from mangling, or an array of identifier names to exclude
 * @property {boolean} [eval=false] - Mangle identifiers in scopes accessible by eval
 * @property {boolean} [keepFnName=false] - Prevent mangler from altering function names (useful for code depending on fn.name)
 * @property {boolean} [topLevel=false] - Mangle top-level identifiers
 * @property {boolean} [keepClassName=false] - Prevent mangler from altering class names
 */

Plugin Usage Patterns

The plugin integrates with Babel's transformation pipeline.

/**
 * Example plugin configurations for different scenarios
 */

// Basic usage - mangle all local variables
const basicConfig = {
  plugins: ["minify-mangle-names"]
};

// Conservative usage - preserve function and class names
const conservativeConfig = {
  plugins: [
    ["minify-mangle-names", {
      keepFnName: true,
      keepClassName: true,
      exclude: { "DEBUG": true }
    }]
  ]
};

// Aggressive usage - mangle top-level variables too
const aggressiveConfig = {
  plugins: [
    ["minify-mangle-names", {
      topLevel: true,
      eval: true
    }]
  ]
};

Advanced Configuration

Excluding Specific Variables

You can exclude specific variable names from being mangled:

// Object format (recommended)
{
  "plugins": [
    ["minify-mangle-names", { 
      "exclude": { 
        "$": true,
        "jQuery": true,
        "GLOBAL_CONFIG": true
      }
    }]
  ]
}

// Array format
{
  "plugins": [
    ["minify-mangle-names", { 
      "exclude": ["$", "jQuery", "GLOBAL_CONFIG"]
    }]
  ]
}

Function and Class Name Preservation

Control whether function and class names are preserved:

// Preserve function names (useful when fn.name is used)
{
  "plugins": [
    ["minify-mangle-names", { "keepFnName": true }]
  ]
}

// Preserve class names
{
  "plugins": [
    ["minify-mangle-names", { "keepClassName": true }]
  ]
}

Top-Level Variable Mangling

Enable mangling of top-level variables (use with caution):

{
  "plugins": [
    ["minify-mangle-names", { "topLevel": true }]
  ]
}

Eval Scope Handling

Control mangling in eval-accessible scopes:

// Mangle variables even in eval-accessible scopes (aggressive)
{
  "plugins": [
    ["minify-mangle-names", { "eval": true }]
  ]
}

Behavior and Limitations

Character Frequency Analysis

The plugin automatically adjusts its behavior based on source code size:

  • Files over 70,000 characters: Performs character frequency analysis of existing identifiers and string literals to optimize variable names for better gzip compression
  • Smaller files: Uses deterministic character generation without frequency analysis to ensure consistent results across single-file builds

Scope Awareness

The plugin respects JavaScript scoping rules:

  • Variables are only renamed within their scope boundaries
  • No naming conflicts are introduced
  • Function parameters and local variables get priority for short names

Safety Guarantees

The plugin maintains code correctness by:

  • Never mangling the arguments object in non-strict mode
  • Preserving label identifiers for break/continue statements
  • Avoiding conflicts with existing global variables
  • Handling class declarations properly (binding in two scopes)
  • Respecting export statements when topLevel is enabled

Performance Optimizations

The plugin includes several optimizations:

  • Character frequency analysis: For files over 70,000 characters, the plugin analyzes character frequency patterns in the source code to generate variable names that improve gzip compression
  • Breadth-first traversal: Ensures consistent renaming patterns across the entire AST
  • Variable name reuse: Short variable names are reused when the original variable name is less than 3 characters long
  • Efficient scope tracking: Advanced scope tracking and collision detection to maintain correctness

Integration with Build Tools

Webpack

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: {
            plugins: [
              ['minify-mangle-names', {
                exclude: { WEBPACK_ENV: true }
              }]
            ]
          }
        }
      }
    ]
  }
};

Rollup

// rollup.config.js
import babel from '@rollup/plugin-babel';

export default {
  plugins: [
    babel({
      plugins: [
        ['minify-mangle-names', {
          topLevel: true,
          keepClassName: true
        }]
      ]
    })
  ]
};