CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-uglifyjs-webpack-plugin

UglifyJS plugin for webpack that provides JavaScript minification with extensive configuration options, caching, and parallel processing support.

Pending
Overview
Eval results
Files

advanced-features.mddocs/

Advanced Features

Performance optimization and customization capabilities for large-scale webpack builds.

Capabilities

Caching System

File-based caching for faster incremental builds and CI/CD pipeline optimization.

/**
 * Enable file caching for faster rebuilds
 * @type {boolean | string}
 * @default false
 */
cache: boolean | string;

/**
 * Override default cache keys for fine-grained cache invalidation control
 * @param {object} defaultCacheKeys - Default cache key object
 * @param {string} file - File path being processed
 * @returns {object} Custom cache keys object for cache invalidation
 * @default (defaultCacheKeys) => defaultCacheKeys
 */
cacheKeys: (defaultCacheKeys: object, file: string) => object;

Cache Configuration Examples:

new UglifyJsPlugin({
  // Enable caching with default directory: node_modules/.cache/uglifyjs-webpack-plugin
  cache: true,
  
  // Custom cache directory
  cache: '/path/to/custom/cache',
  
  // Custom cache keys for advanced cache invalidation
  cacheKeys: (defaultCacheKeys, file) => ({
    ...defaultCacheKeys,
    buildVersion: process.env.BUILD_VERSION,
    customConfig: myCustomConfig,
  }),
})

Default Cache Keys:

  • 'uglify-js': UglifyJS package version
  • 'uglifyjs-webpack-plugin': Plugin version
  • 'uglifyjs-webpack-plugin-options': Plugin configuration hash
  • hash: MD4 hash of input file content
  • node_version: Node.js version

Cache Behavior:

  • Cache hits skip minification and return cached results
  • Cache misses trigger minification and store results
  • Cache invalidation occurs when any cache key changes
  • Cached results include: code, map, warnings, extractedComments

Parallel Processing

Multi-process parallel execution for improved build performance on multi-core systems.

/**
 * Use multi-process parallel running to improve build speed
 * @type {boolean | number}
 * @default false
 */
parallel: boolean | number;

Parallel Configuration Examples:

new UglifyJsPlugin({
  // Enable parallel processing (uses os.cpus().length - 1 workers)
  parallel: true,
  
  // Custom number of parallel workers
  parallel: 4,
  
  // Disable parallel processing
  parallel: false,
})

Parallel Processing Details:

  • Worker Farm: Uses worker-farm package for process management
  • Default Workers: os.cpus().length - 1 (leaves one CPU core free)
  • WSL Limitation: Forced to single worker on Windows Subsystem for Linux
  • Windows Optimization: Uses maxConcurrentCallsPerWorker: 1 for stability
  • Task Distribution: Distributes file processing tasks across worker processes
  • Memory Management: Each worker process handles serialized task data

Performance Considerations:

  • Most effective with large numbers of files (>10)
  • Overhead costs may outweigh benefits for small bundles
  • Combines well with caching for optimal performance
  • Memory usage increases with worker count

Custom Minification Functions

Replace default UglifyJS with custom minification implementations for specialized use cases.

/**
 * Custom minify function to override default UglifyJS behavior
 * Must return MinifyResult object with expected properties
 * Always use require() inside function when parallel processing is enabled
 * @param {object} file - Object with filename as key and source as value
 * @param {object} sourceMap - Input source map object (if available)
 * @returns {MinifyResult} Minification result with code, map, warnings, etc.
 */
minify: (file: object, sourceMap?: object) => MinifyResult;

interface MinifyResult {
  /** Minification error (if any) */
  error?: Error;
  /** Generated source map string */
  map?: string;
  /** Minified code string */
  code?: string;
  /** Array of warning messages */
  warnings?: string[];
  /** Array of extracted comment strings */
  extractedComments?: string[];
}

Custom Minification Examples:

Using Terser (UglifyJS alternative):

new UglifyJsPlugin({
  minify(file, sourceMap) {
    const terserOptions = {
      compress: {
        drop_console: true,
      },
      mangle: true,
    };
    
    if (sourceMap) {
      terserOptions.sourceMap = {
        content: sourceMap,
      };
    }
    
    return require('terser').minify(file, terserOptions);
  },
})

Using esbuild for faster minification:

new UglifyJsPlugin({
  minify(file, sourceMap) {
    const esbuild = require('esbuild');
    const filename = Object.keys(file)[0];
    const source = file[filename];
    
    try {
      const result = esbuild.transformSync(source, {
        minify: true,
        sourcemap: !!sourceMap,
      });
      
      return {
        code: result.code,
        map: result.map,
        warnings: [],
        extractedComments: [],
      };
    } catch (error) {
      return {
        error: error,
      };
    }
  },
})

Using custom preprocessing:

new UglifyJsPlugin({
  minify(file, sourceMap) {
    const uglify = require('uglify-js');
    const filename = Object.keys(file)[0];
    let source = file[filename];
    
    // Custom preprocessing
    source = source.replace(/console\.debug\([^)]*\);?/g, '');
    source = source.replace(/\/\*\s*@debug\s*\*\/[\s\S]*?\/\*\s*@\/debug\s*\*\//g, '');
    
    const options = {
      compress: {
        drop_console: false, // We already removed debug console calls
      },
      sourceMap: sourceMap ? { content: sourceMap } : false,
    };
    
    return uglify.minify({ [filename]: source }, options);
  },
})

Important Notes for Custom Minification:

  • Always use require() inside the function when parallel: true
  • Must return object with MinifyResult interface
  • Handle errors by returning { error: Error } object
  • Source map handling is optional but recommended
  • Function is serialized for worker processes (no closure variables)

Cache Invalidation Strategies

Advanced cache key customization for complex build scenarios.

/**
 * Advanced cache key customization for complex invalidation scenarios
 * @param {object} defaultCacheKeys - Plugin's default cache keys
 * @param {string} file - Current file path being processed
 * @returns {object} Enhanced cache keys object
 */
cacheKeys: (defaultCacheKeys: object, file: string) => object;

Cache Invalidation Examples:

Environment-based invalidation:

new UglifyJsPlugin({
  cache: true,
  cacheKeys: (defaultCacheKeys, file) => ({
    ...defaultCacheKeys,
    nodeEnv: process.env.NODE_ENV,
    buildId: process.env.BUILD_ID,
    gitCommit: process.env.GIT_COMMIT,
  }),
})

File-specific invalidation:

new UglifyJsPlugin({
  cache: true,
  cacheKeys: (defaultCacheKeys, file) => {
    const keys = { ...defaultCacheKeys };
    
    // Different cache strategy for vendor vs app files
    if (file.includes('vendor')) {
      keys.vendorVersion = require('./package.json').dependencies;
    } else {
      keys.appVersion = require('./package.json').version;
    }
    
    return keys;
  },
})

Configuration-based invalidation:

new UglifyJsPlugin({
  cache: true,
  cacheKeys: (defaultCacheKeys, file) => ({
    ...defaultCacheKeys,
    webpackConfig: crypto
      .createHash('md5')
      .update(JSON.stringify(webpackConfig))
      .digest('hex'),
    customMinifyOptions: JSON.stringify(customOptions),
  }),
})

Performance Optimization Patterns

Recommended configurations for different build scenarios.

Development builds (fast iteration):

new UglifyJsPlugin({
  cache: true,
  parallel: true,
  sourceMap: true,
  uglifyOptions: {
    warnings: false,
    compress: false,
    mangle: false,
  },
})

Production builds (maximum optimization):

new UglifyJsPlugin({
  cache: true,
  parallel: true,
  sourceMap: false,
  extractComments: true,
  uglifyOptions: {
    compress: {
      drop_console: true,
      drop_debugger: true,
      pure_funcs: ['console.log', 'console.info'],
    },
    mangle: {
      toplevel: true,
    },
    output: {
      comments: false,
    },
  },
})

CI/CD builds (reproducible and cached):

new UglifyJsPlugin({
  cache: '/shared/cache/uglifyjs',
  parallel: Math.min(4, os.cpus().length - 1),
  cacheKeys: (defaultCacheKeys) => ({
    ...defaultCacheKeys,
    buildNumber: process.env.BUILD_NUMBER,
    nodeVersion: process.version,
  }),
})

Install with Tessl CLI

npx tessl i tessl/npm-uglifyjs-webpack-plugin

docs

advanced-features.md

configuration.md

index.md

plugin-methods.md

tile.json