CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-terser

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

Pending
Overview
Eval results
Files

advanced.mddocs/

Advanced Features

Advanced functionality including AST manipulation, custom identifier mangling, default option introspection, and SpiderMonkey AST support for specialized use cases and deep integrations.

Capabilities

Default Options Introspection

Retrieve complete default configuration for all Terser components, useful for option discovery and configuration validation.

/**
 * Get default options for all Terser components
 * @returns Promise resolving to object containing default options for each component
 */
async function _default_options(): Promise<object>;

Usage Examples:

import { _default_options } from "terser";

// Discover available options
const defaults = await _default_options();
console.log(defaults);
// Output includes: compress, mangle, format, parse, etc.

// Use as base for custom configuration
const customOptions = {
  ...defaults.compress,
  drop_console: true,
  passes: 3
};

Custom Identifier Mangling

Advanced name mangling system supporting custom identifier generation algorithms and character frequency analysis.

/**
 * Simple identifier mangler interface for deterministic name generation
 */
interface SimpleIdentifierMangler {
  /**
   * Generate the nth most preferred identifier name
   * @param n - Ordinal identifier index (0-based)
   * @returns Generated identifier name
   */
  get(n: number): string;
}

/**
 * Advanced identifier mangler with character frequency optimization
 */
interface WeightedIdentifierMangler extends SimpleIdentifierMangler {
  /**
   * Adjust character frequency weights based on input analysis
   * @param chars - Characters to analyze
   * @param delta - Weight adjustment value
   * @returns Updated weight value
   */
  consider(chars: string, delta: number): number;
  
  /**
   * Reset all character frequency weights to initial state
   */
  reset(): void;
  
  /**
   * Sort identifiers by frequency for optimal compression
   */
  sort(): void;
}

Usage Examples:

// Simple custom mangler
class CustomMangler implements SimpleIdentifierMangler {
  get(n: number): string {
    // Generate custom identifier names
    return `_${n.toString(36)}`;
  }
}

// Use with mangle options
await minify(code, {
  mangle: {
    nth_identifier: new CustomMangler()
  }
});

// Weighted mangler for frequency optimization
class FrequencyMangler implements WeightedIdentifierMangler {
  private weights = new Map<string, number>();
  
  get(n: number): string {
    // Implementation based on character frequency
    return this.generateFromWeights(n);
  }
  
  consider(chars: string, delta: number): number {
    // Adjust weights based on character usage
    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 {
    // Sort by frequency for optimal identifier generation
  }
}

Property Mangling Options

Advanced property name mangling with regex filtering, builtin handling, and debugging support.

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

Usage Examples:

await minify(code, {
  mangle: {
    properties: {
      // Only mangle private-style properties
      regex: /^_/,
      reserved: ['_config', '_internal'],
      debug: true  // Add debug markers
    }
  }
});

// Strict quoted property handling
await minify(code, {
  mangle: {
    properties: {
      keep_quoted: 'strict',  // Never mangle quoted properties
      builtins: false         // Preserve builtin property names
    }
  }
});

Source Map Integration

Advanced source map configuration for complex build scenarios and debugging workflows.

interface SourceMapOptions {
  /** Input source map content */
  content?: SectionedSourceMapInput | string;
  /** Include original source content in map */
  includeSources?: boolean;
  /** Output filename for source map */
  filename?: string;
  /** Source root path */
  root?: string;
  /** Return source map as object instead of JSON string */
  asObject?: boolean;
  /** Source map URL or 'inline' for data URI */
  url?: string | 'inline';
}

Usage Examples:

// Chain source maps through build pipeline
const previousMap = JSON.parse(fs.readFileSync('input.js.map', 'utf8'));

const result = await minify(code, {
  sourceMap: {
    content: previousMap,     // Chain from previous step
    filename: 'output.js.map',
    includeSources: true,     // Embed original sources
    root: '/src'             // Source root for debugging
  }
});

// Inline source map for development
const devResult = await minify(code, {
  sourceMap: {
    url: 'inline',           // Embed as data URI
    includeSources: true
  }
});

AST Processing and Mozilla Support

Support for SpiderMonkey AST format and direct AST manipulation for advanced use cases.

// AST input/output support through parse options
interface ParseOptions {
  /** Parse input as SpiderMonkey AST format */
  spidermonkey?: boolean;
}

interface FormatOptions {
  /** Output SpiderMonkey AST instead of code */
  spidermonkey?: boolean;
  /** Include AST in output object */
  ast?: boolean;
}

Usage Examples:

// Process SpiderMonkey AST
const spidermonkeyAST = { /* SpiderMonkey AST object */ };

const result = await minify(spidermonkeyAST, {
  parse: { spidermonkey: true },
  format: { spidermonkey: true }
});
// result.ast contains processed SpiderMonkey AST

// Preserve AST for further processing
const withAST = await minify(code, {
  format: { ast: true }
});
// withAST.ast contains Terser AST object

Name Cache Management

Persistent caching system for consistent identifier mangling across multiple builds.

interface NameCacheObject {
  /** Variable name mappings */
  vars?: { [originalName: string]: string };
  /** Property name mappings */
  props?: { [originalName: string]: string };
}

Usage Examples:

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

const result = await minify(code, {
  nameCache,
  mangle: {
    cache: nameCache.vars || {}
  }
});

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

// Separate caches for different build targets
const prodCache = { vars: {}, props: {} };
const devCache = { vars: {}, props: {} };

Error and Debug Information

Advanced error handling and debugging capabilities for development and troubleshooting.

// Enable debug logging via environment variable
process.env.TERSER_DEBUG_DIR = './debug';

try {
  const result = await minify(code, {
    timings: true  // Include timing information
  });
  
  console.log('Processing times:', result.timings);
  // Output: { parse: 0.123, compress: 0.456, mangle: 0.078, ... }
  
} catch (error) {
  // Detailed error information
  console.error('Line:', error.line);
  console.error('Column:', error.col);
  console.error('Context:', error.filename);
}

Utility Functions

Base64 decoding utility for working with inline source maps and encoded content.

/**
 * Decode base64-encoded strings to ASCII
 * @param base64 - Base64-encoded string
 * @returns Decoded ASCII string
 */
function to_ascii(base64: string): string;

Usage Examples:

import { to_ascii } from "terser";

// Decode inline source map
const inlineMap = "eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9";
const decoded = to_ascii(inlineMap);
console.log(JSON.parse(decoded)); // Source map object

Performance Optimization

Advanced techniques for optimizing Terser performance in production environments:

Compression Passes

// Multiple compression passes for maximum optimization
const result = await minify(code, {
  compress: {
    passes: 3,           // Multiple optimization passes
    pure_funcs: [        // Mark functions as pure for removal
      'console.log',
      'debug.log'
    ]
  }
});

Parallel Processing

// Process multiple files in parallel
const files = ['file1.js', 'file2.js', 'file3.js'];
const results = await Promise.all(
  files.map(file => 
    minify(fs.readFileSync(file, 'utf8'), options)
  )
);

Memory Management

// Minimize memory usage for large codebases
const result = await minify(code, {
  format: {
    ast: false,          // Don't preserve AST
    comments: false      // Remove comments
  }
});

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