CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-terser

JavaScript parser, mangler/compressor and beautifier toolkit for ES6+

Pending
Overview
Eval results
Files

mangling.mddocs/

Name Mangling

Advanced name obfuscation system providing variable, function, and property name shortening with customizable preservation rules and identifier generation algorithms for maximum code size reduction.

Capabilities

Mangle Options

Core name mangling configuration controlling variable, function, and property name transformation.

interface MangleOptions {
  /** Mangle names in eval scope (risky) */
  eval?: boolean;
  /** Preserve class names during mangling */
  keep_classnames?: boolean | RegExp;
  /** Preserve function names during mangling */
  keep_fnames?: boolean | RegExp;
  /** Treat code as ES6 module */
  module?: boolean;
  /** Custom identifier generation algorithm */
  nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler;
  /** Enable/configure property name mangling */
  properties?: boolean | ManglePropertiesOptions;
  /** Names to exclude from mangling */
  reserved?: string[];
  /** Safari 10 compatibility mode */
  safari10?: boolean;
  /** Apply mangling to top-level scope */
  toplevel?: boolean;
}

Basic Variable Mangling

Standard variable and function name shortening for local scopes.

Usage Examples:

// Basic mangling
const result = await minify(code, {
  mangle: true  // Enable with default settings
});

// Custom mangling options
const result = await minify(code, {
  mangle: {
    reserved: ['$', 'jQuery', 'angular'],  // Don't mangle these names
    keep_fnames: true,                     // Preserve function names
    keep_classnames: /^Component/          // Preserve class names matching regex
  }
});

// Before: function calculateTotalPrice(items) { var sum = 0; return sum; }
// After:  function calculateTotalPrice(e) { var a = 0; return a; }

Top-level Mangling

Mangle names in global/top-level scope for maximum compression.

Usage Examples:

// Enable top-level mangling
const result = await minify(code, {
  mangle: {
    toplevel: true  // Mangle global variables and functions
  }
});

// Module-aware mangling
const result = await minify(code, {
  mangle: {
    module: true,    // ES6 module mode
    toplevel: true   // Safe for modules
  }
});

// Before: var globalConfig = {}; function initApp() {}
// After:  var a = {}; function b() {}

Property Mangling

Advanced property name obfuscation with regex filtering and preservation rules.

interface ManglePropertiesOptions {
  /** Mangle properties that overlap with built-in JavaScript names */
  builtins?: boolean;
  /** Add debug prefix/suffix to mangled property names */
  debug?: boolean;
  /** Handle quoted property names */
  keep_quoted?: boolean | 'strict';
  /** Custom identifier generation for properties */
  nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler;
  /** Only mangle properties matching this pattern */
  regex?: RegExp | string;
  /** Property names to exclude from mangling */
  reserved?: string[];
}

Usage Examples:

// Basic property mangling
const result = await minify(code, {
  mangle: {
    properties: true  // Mangle all properties
  }
});

// Selective property mangling
const result = await minify(code, {
  mangle: {
    properties: {
      regex: /^_/,              // Only mangle private-style properties
      reserved: ['_config'],     // But preserve _config
      keep_quoted: true         // Don't mangle quoted properties
    }
  }
});

// Advanced property mangling
const result = await minify(code, {
  mangle: {
    properties: {
      regex: /^(get|set)_/,     // Mangle getters/setters
      debug: true,              // Add debug info
      builtins: false          // Don't mangle built-in names
    }
  }
});

// Before: obj._privateMethod(); obj["public_api"]();
// After:  obj.a(); obj["public_api"]();  // quoted preserved

Name Reservation

Comprehensive name preservation system for external APIs and required identifiers.

Usage Examples:

// Framework integration
const result = await minify(code, {
  mangle: {
    reserved: [
      // jQuery
      '$', 'jQuery',
      // Angular
      'angular', 'module', 'controller',
      // React
      'React', 'Component', 'render',
      // Custom API
      'MyLibrary', 'PUBLIC_API'
    ]
  }
});

// RegExp-based preservation
const result = await minify(code, {
  mangle: {
    keep_fnames: /^(init|destroy|render)$/,    // Preserve lifecycle methods
    keep_classnames: /Component$/,              // Preserve component classes
    reserved: ['CONSTANTS', 'CONFIG']           // Preserve specific names
  }
});

Custom Identifier Generation

Advanced identifier generation with pluggable algorithms and frequency optimization.

/**
 * Simple identifier mangler interface
 */
interface SimpleIdentifierMangler {
  /**
   * Generate identifier for given ordinal
   * @param n - Zero-based identifier index
   * @returns Generated identifier string
   */
  get(n: number): string;
}

/**
 * Weighted identifier mangler with frequency analysis
 */
interface WeightedIdentifierMangler extends SimpleIdentifierMangler {
  /**
   * Update character frequency weights
   * @param chars - Characters to analyze
   * @param delta - Weight adjustment
   * @returns Updated weight
   */
  consider(chars: string, delta: number): number;
  
  /** Reset frequency analysis */
  reset(): void;
  
  /** Sort identifiers by frequency */
  sort(): void;
}

Usage Examples:

// Custom simple mangler
class PrefixMangler implements SimpleIdentifierMangler {
  get(n: number): string {
    return `_${n.toString(36)}`;  // _0, _1, _2, ...
  }
}

// Frequency-based mangler
class FrequencyMangler implements WeightedIdentifierMangler {
  private weights = new Map<string, number>();
  
  get(n: number): string {
    // Generate based on character frequency
    return this.generateOptimal(n);
  }
  
  consider(chars: string, delta: number): number {
    // Track character usage patterns
    for (const char of chars) {
      const current = this.weights.get(char) || 0;
      this.weights.set(char, current + delta);
    }
    return delta;
  }
  
  reset(): void {
    this.weights.clear();
  }
  
  sort(): void {
    // Optimize identifier order by frequency
  }
}

// Use custom mangler
const result = await minify(code, {
  mangle: {
    nth_identifier: new PrefixMangler()
  }
});

Name Cache Persistence

Consistent name mapping across multiple builds and incremental compilation.

Usage Examples:

// Load previous name cache
const nameCache = JSON.parse(fs.readFileSync('names.json', 'utf8'));

const result = await minify(code, {
  nameCache,  // Use existing mappings
  mangle: true
});

// Save updated cache
fs.writeFileSync('names.json', JSON.stringify(result.nameCache));

// Separate caches for different targets
const libCache = { vars: {}, props: {} };
const appCache = { vars: {}, props: {} };

// Library build
const libResult = await minify(libCode, {
  nameCache: libCache,
  mangle: { toplevel: false }  // Don't mangle exports
});

// Application build  
const appResult = await minify(appCode, {
  nameCache: appCache,
  mangle: { toplevel: true }   // Mangle everything
});

Safari and IE Compatibility

Special handling for browser compatibility issues with name mangling.

Usage Examples:

// Safari 10 compatibility
const result = await minify(code, {
  mangle: {
    safari10: true  // Avoid Safari 10 mangling bugs
  }
});

// IE8 compatibility
const result = await minify(code, {
  mangle: {
    reserved: ['default']  // IE8 keyword issues
  },
  compress: {
    ie8: true
  }
});

Eval Scope Mangling

Risky but powerful mangling for code using eval and dynamic execution.

Usage Examples:

// Conservative approach (default)
const result = await minify(code, {
  mangle: {
    eval: false  // Don't mangle in eval scope (safe)
  }
});

// Aggressive approach (risky)
const result = await minify(code, {
  mangle: {
    eval: true  // Mangle even in eval scope (may break code)
  }
});

Types

interface MangleOptions {
  eval?: boolean;
  keep_classnames?: boolean | RegExp;
  keep_fnames?: boolean | RegExp;
  module?: boolean;
  nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler;
  properties?: boolean | ManglePropertiesOptions;
  reserved?: string[];
  safari10?: boolean;
  toplevel?: boolean;
}

interface ManglePropertiesOptions {
  builtins?: boolean;
  debug?: boolean;
  keep_quoted?: boolean | 'strict';
  nth_identifier?: SimpleIdentifierMangler | WeightedIdentifierMangler;
  regex?: RegExp | string;
  reserved?: string[];
}

Install with Tessl CLI

npx tessl i tessl/npm-terser

docs

advanced.md

cli.md

compression.md

configuration.md

formatting.md

index.md

mangling.md

minification.md

tile.json