or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-parcel--optimizer-terser

A Parcel optimizer plugin that uses Terser to minify JavaScript code for production builds.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@parcel/optimizer-terser@2.15.x

To install, run

npx @tessl/cli install tessl/npm-parcel--optimizer-terser@2.15.0

index.mddocs/

Parcel Terser Optimizer

A Parcel optimizer plugin that uses Terser to minify JavaScript code for production builds. This plugin integrates with Parcel's optimization pipeline to compress and optimize JavaScript bundles with advanced minification techniques.

Package Information

  • Package Name: @parcel/optimizer-terser
  • Package Type: npm
  • Language: JavaScript (Flow typed)
  • Installation: This is a Parcel plugin, typically included automatically in Parcel builds

Core Imports

This package is designed as a Parcel plugin and is not directly imported by user code. Instead, it is automatically loaded by Parcel during the build process when JavaScript optimization is enabled.

For Parcel configuration:

// .parcelrc
{
  "optimizers": {
    "*.js": ["@parcel/optimizer-terser"]
  }
}

Basic Usage

The plugin is used automatically by Parcel during production builds. It can be configured through standard Terser configuration files:

// .terserrc.js
module.exports = {
  compress: {
    drop_console: true,
    drop_debugger: true
  },
  mangle: {
    toplevel: true
  },
  format: {
    comments: false
  }
};

Architecture

The Parcel Terser Optimizer is built on Parcel's plugin architecture:

  • Plugin System: Extends Parcel's Optimizer base class from @parcel/plugin
  • Configuration Loading: Automatically discovers and loads Terser configuration files
  • Bundle Processing: Integrates with Parcel's bundle objects and file system
  • Error Handling: Provides enhanced error reporting with source map integration
  • Source Map Support: Preserves and transforms source maps during minification

Capabilities

Plugin Export

The main export is a configured Parcel Optimizer instance that handles JavaScript minification.

/**
 * Default export: Configured Parcel Optimizer instance
 * Contains loadConfig and optimize methods for JavaScript minification
 */
declare const TerserOptimizer: Optimizer;
export default TerserOptimizer;

Configuration Loading

Loads user configuration from standard Terser configuration files.

/**
 * Loads Terser configuration from project configuration files
 * @param {Object} context - Parcel configuration context
 * @param {Object} context.config - Parcel config loader
 * @param {Object} context.options - Parcel build options
 * @returns {Promise<Object|undefined>} User configuration or undefined
 */
async function loadConfig({ config, options });

Supported configuration files:

  • .terserrc - JSON configuration
  • .terserrc.js - JavaScript configuration (CommonJS)
  • .terserrc.cjs - JavaScript configuration (CommonJS)
  • .terserrc.mjs - JavaScript configuration (ES modules)

Bundle Optimization

Performs JavaScript minification using Terser with comprehensive error handling.

/**
 * Optimizes JavaScript bundle contents using Terser
 * @param {Object} context - Optimization context
 * @param {Blob} context.contents - Bundle contents to optimize
 * @param {SourceMap} context.map - Source map for the bundle
 * @param {Bundle} context.bundle - Bundle metadata and configuration
 * @param {Object} context.config - User configuration from loadConfig
 * @param {Object} context.options - Parcel build options
 * @param {Function} context.getSourceMapReference - Source map reference generator
 * @returns {Promise<{contents: string, map: SourceMap}>} Optimized bundle
 */
async function optimize({
  contents,
  map,
  bundle,
  config,
  options,
  getSourceMapReference
});

Configuration Options

The plugin accepts all standard Terser configuration options through configuration files:

Compression Options

{
  compress: {
    dead_code: true,        // Remove unreachable code
    drop_console: false,    // Remove console statements
    drop_debugger: true,    // Remove debugger statements
    keep_fargs: false,      // Keep function arguments
    passes: 1,              // Number of compression passes
    unsafe: false           // Enable unsafe optimizations
  }
}

Mangling Options

{
  mangle: {
    toplevel: false,        // Mangle top-level names (auto-set based on output format)
    properties: false,      // Mangle property names
    keep_fnames: false,     // Keep function names
    safari10: false         // Safari 10 compatibility
  }
}

Output Format Options

{
  format: {
    comments: false,        // Preserve comments
    beautify: false,        // Beautify output
    indent_level: 2,        // Indentation level
    semicolons: true,       // Use semicolons
    shorthand: true         // Use shorthand properties
  }
}

Source Map Options

Source map options are automatically configured based on Parcel's environment settings:

{
  sourceMap: {
    filename: "bundle.js",  // Output filename (auto-generated)
    asObject: true,         // Return source map as object
    content: "...",         // Input source map content
  }
}

Environment Integration

The plugin integrates with Parcel's build environment:

Build Conditions

/**
 * Environment conditions that affect optimization behavior
 */
interface BuildEnvironment {
  /** Whether optimization should be performed (production builds) */
  shouldOptimize: boolean;
  /** Whether source maps should be generated */
  sourceMap: boolean;
  /** Output format for module-specific optimizations */
  outputFormat: 'esmodule' | 'commonjs' | 'global';
}

Optimization Features

  • Conditional Optimization: Only runs in production builds (bundle.env.shouldOptimize)
  • Format-Specific Options: Adjusts toplevel and module settings based on output format
  • Source Map Integration: Preserves and transforms source maps when enabled
  • Error Recovery: Provides detailed error reporting with code frames and hints

Error Handling

The plugin provides comprehensive error handling with enhanced diagnostics:

Error Types

/**
 * Enhanced error reporting for Terser optimization failures
 */
interface TerserError {
  /** Error message from Terser */
  message: string;
  /** Line number in the processed code */
  line?: number;
  /** Column number in the processed code */
  col?: number;
}

/**
 * Diagnostic information for error reporting
 */
interface ErrorDiagnostic {
  /** Human-readable error message */
  message: string;
  /** Plugin origin identifier */
  origin: '@parcel/optimizer-terser';
  /** Code frames showing error location */
  codeFrames: CodeFrame[];
  /** Helpful hints for resolving the error */
  hints: string[];
}

Error Features

  • Source Map Error Mapping: Maps errors back to original source locations when possible
  • Code Frame Generation: Shows relevant code context around errors
  • Helpful Hints: Provides suggestions for common Terser compatibility issues
  • Dual Error Reporting: Shows both original and transformed code locations in verbose mode

Types

/**
 * Parcel Bundle object containing metadata and configuration
 */
interface Bundle {
  /** Bundle name and file information */
  name: string;
  /** Target build configuration */
  target: {
    distDir: string;
  };
  /** Environment configuration */
  env: {
    shouldOptimize: boolean;
    sourceMap: boolean;
    outputFormat: 'esmodule' | 'commonjs' | 'global';
  };
}

/**
 * Parcel build options and configuration
 */
interface ParcelOptions {
  /** Project root directory */
  projectRoot: string;
  /** File system abstraction */
  inputFS: FileSystem;
  /** Logging level configuration */
  logLevel: 'none' | 'error' | 'warn' | 'info' | 'verbose';
}

/**
 * Parcel file system abstraction
 */
interface FileSystem {
  readFile(filePath: string, encoding: string): Promise<string>;
}

/**
 * Parcel source map handling
 */
interface SourceMap {
  stringify(options: object): Promise<string>;
  addVLQMap(map: object): void;
}

/**
 * Parcel Optimizer base class
 */
interface Optimizer {
  loadConfig(context: {config: any, options: ParcelOptions}): Promise<any>;
  optimize(context: OptimizeContext): Promise<OptimizationResult>;
}

/**
 * Optimization context passed to optimize method
 */
interface OptimizeContext {
  contents: Blob;
  map: SourceMap | null;
  bundle: Bundle;
  config: any;
  options: ParcelOptions;
  getSourceMapReference: SourceMapReferenceGenerator;
}

/**
 * Blob represents bundle contents
 */
interface Blob {
  // Internal Parcel representation of file contents
}

/**
 * Code frame for error reporting
 */
interface CodeFrame {
  language: string;
  filePath?: string;
  code: string;
  codeHighlights: Array<{
    message: string;
    start: {line: number, column: number};
    end: {line: number, column: number};
  }>;
}

/**
 * Source map reference generator function
 */
interface SourceMapReferenceGenerator {
  (sourceMap: SourceMap): Promise<string>;
}

/**
 * Optimization result containing minified code and source map
 */
interface OptimizationResult {
  /** Minified JavaScript code */
  contents: string;
  /** Transformed source map (if enabled) */
  map: SourceMap | null;
}