or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

grunt-contrib-uglify

Grunt plugin that minifies JavaScript files using UglifyJS with comprehensive options and source map support. It integrates seamlessly into Grunt build workflows, providing JavaScript compression, variable mangling, and production optimization capabilities.

Package Information

  • Package Name: grunt-contrib-uglify
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install grunt-contrib-uglify --save-dev

Core Imports

// In your Gruntfile.js
grunt.loadNpmTasks('grunt-contrib-uglify');

Basic Usage

Configure the uglify task in your Gruntfile.js:

module.exports = function(grunt) {
  grunt.initConfig({
    uglify: {
      options: {
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
      },
      build: {
        src: 'src/*.js',
        dest: 'build/<%= pkg.name %>.min.js'
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.registerTask('default', ['uglify']);
};

Run the task:

grunt uglify

Architecture

grunt-contrib-uglify consists of two main components:

  • Main Task Plugin (tasks/uglify.js): Registers the 'uglify' Grunt multi-task and handles file processing, options validation, and result reporting
  • UglifyJS Wrapper (tasks/lib/uglify.js): Wraps UglifyJS functionality with Grunt-specific features like file handling, source maps, and name caching

The plugin integrates with Grunt's file configuration system, supports glob patterns, and provides detailed compression statistics.

Capabilities

Task Registration

The main plugin function that registers the 'uglify' task with Grunt.

/**
 * Main plugin export function that registers the uglify task
 * @param {Object} grunt - The Grunt instance
 */
function uglifyPlugin(grunt: Object): void;

Uglify Task Options

Core configuration options for the uglify task.

interface UglifyOptions {
  /** Banner text to prepend to the output */
  banner?: string;
  
  /** Footer text to append to the output */  
  footer?: string;
  
  /** UglifyJS compression options */
  compress?: boolean | Object;
  
  /** Variable name mangling options */
  mangle?: boolean | MangleOptions;
  
  /** Output beautification options */
  beautify?: boolean | Object;
  
  /** Minification result reporting level */
  report?: 'min' | 'gzip';
  
  /** IE8 compatibility mode */
  ie8?: boolean;
  
  /** Source map generation options */
  sourceMap?: boolean | Object;
  
  /** Custom source map filename or generator function */
  sourceMapName?: string | Function;
  
  /** Input source map file or generator function */
  sourceMapIn?: string | Function;
}

Source Map Configuration

Source map generation and customization options.

interface SourceMapOptions {
  /** Include sources content in the source map */
  includeSources?: boolean;
  
  /** Custom root path for source map */
  root?: string;
  
  /** Custom URL for source map reference */
  url?: string;
  
  /** Custom filename for the generated source map */
  filename?: string;
  
  /** Existing source map content to include */
  content?: string;
}

Advanced Options

Additional configuration options for specialized use cases.

interface AdvancedOptions {
  /** Path to name cache file for consistent variable renaming */
  nameCache?: string;
  
  /** Reserve DOM property names from mangling */
  reserveDOMProperties?: boolean;
  
  /** JSON files containing variables/properties to exclude from mangling */
  exceptionsFiles?: string[];
  
  /** Preserve function names during minification */
  keep_fnames?: boolean;
  
  /** Enable top-level variable/function name mangling */
  toplevel?: boolean;
  
  /** Wrap output in specified function call */
  wrap?: string | boolean;
  
  /** UglifyJS parser options */
  parse?: ParseOptions;
  
  /** UglifyJS output formatting options */
  output?: OutputOptions;
}

interface ParseOptions {
  /** Parse a single expression rather than a program (for parsing JSON) */
  expression?: boolean;
}

interface MangleOptions {
  /** Array of variable names to exclude from mangling */
  reserved?: string[];
  
  /** Property mangling options */
  properties?: boolean | ManglePropertiesOptions;
  
  /** Enable top-level variable/function name mangling */
  toplevel?: boolean;
}

interface ManglePropertiesOptions {
  /** Array of property names to exclude from mangling */
  reserved?: string[];
  
  /** Regular expression to match property names that should be mangled */
  regex?: RegExp;
  
  /** Internal cache object for coordinating property name mangling (managed automatically) */
  cache?: Object;
}

interface OutputOptions {
  /** Encode non-ASCII characters as \uXXXX */
  ascii_only?: boolean;
  
  /** Comment preservation options */
  comments?: boolean | string | Function | RegExp;
  
  /** Style of quotes to use (0=auto, 1=single, 2=double, 3=original) */
  quote_style?: 0 | 1 | 2 | 3;
  
  /** Maximum line length */
  max_line_len?: number;
  
  /** Indentation level */
  indent_level?: number;
}

Minification Result

The result object returned by the internal minify function.

interface MinifyResult {
  /** Original unminified code concatenated */
  max: string;
  
  /** Minified JavaScript code */
  min: string;
  
  /** Generated source map content */
  sourceMap: string;
}

Usage Examples

Basic Minification

Simple file minification with default options:

grunt.initConfig({
  uglify: {
    my_target: {
      files: {
        'dest/output.min.js': ['src/input.js']
      }
    }
  }
});

Advanced Configuration

Comprehensive configuration with multiple options:

grunt.initConfig({
  uglify: {
    options: {
      mangle: {
        reserved: ['jQuery', '$']
      },
      compress: {
        drop_console: true,
        drop_debugger: true
      },
      banner: '/*! My Library v1.0.0 */\n',
      sourceMap: true,
      sourceMapName: 'dest/output.min.js.map'
    },
    target: {
      files: {
        'dest/output.min.js': ['src/file1.js', 'src/file2.js']
      }
    }
  }
});

Source Map Generation

Enable source maps with custom configuration:

grunt.initConfig({
  uglify: {
    options: {
      sourceMap: {
        includeSources: true,
        root: '../src/'
      },
      sourceMapName: function(dest) {
        return dest + '.map';
      }
    },
    build: {
      files: {
        'build/app.min.js': ['src/app.js', 'src/utils.js']
      }
    }
  }
});

Multiple Targets

Configure different minification strategies for different file sets:

grunt.initConfig({
  uglify: {
    development: {
      options: {
        beautify: true,
        mangle: false,
        compress: false
      },
      files: {
        'build/dev/app.js': ['src/*.js']
      }
    },
    production: {
      options: {
        compress: {
          drop_console: true
        },
        mangle: true,
        report: 'gzip'
      },
      files: {
        'build/prod/app.min.js': ['src/*.js']
      }
    }
  }
});

Name Cache for Consistent Builds

Use name caching for consistent variable names across builds:

grunt.initConfig({
  uglify: {
    options: {
      nameCache: '.tmp/grunt-uglify-cache.json',
      mangle: {
        properties: true
      }
    },
    build: {
      files: {
        'dist/library.min.js': ['src/*.js']
      }
    }
  }
});

Property Mangling with Exceptions

Mangle properties while preserving specific names:

grunt.initConfig({
  uglify: {
    options: {
      mangle: {
        properties: {
          reserved: ['prototype', 'constructor', 'length']
        }
      },
      reserveDOMProperties: true,
      exceptionsFiles: ['exceptions.json']
    },
    build: {
      files: {
        'dist/app.min.js': ['src/*.js']
      }
    }
  }
});

Property Mangling with Regular Expression Filter

Mangle only properties matching a specific pattern:

grunt.initConfig({
  uglify: {
    options: {
      mangle: {
        properties: {
          // Only mangle properties that don't start with #
          regex: /^[^#].*/
        }
      }
    },
    build: {
      files: {
        'dist/app.min.js': ['src/*.js']
      }
    }
  }
});

This configuration will mangle properties like myProperty but preserve properties like #publicAPI.

Example exceptions.json file:

{
  "vars": ["myGlobalVar", "CONSTANTS"],
  "props": ["publicMethod", "apiEndpoint"]
}

Error Handling

The plugin provides detailed error reporting for common issues:

  • Missing source files: Warns when specified source files don't exist
  • UglifyJS errors: Reports syntax errors with line numbers and file names
  • Source map errors: Handles source map generation failures gracefully
  • Function generation errors: Catches errors in custom sourceMapName and sourceMapIn functions

Example error output:

Warning: Source file 'src/missing.js' not found
Warning: Uglifying source src/broken.js failed.
>> Uglification failed.
>> Unexpected token: name (myVar)
>> Line 15 in src/broken.js

Task Output

The plugin provides informative output about the minification process:

Running "uglify:build" (uglify) task
File build/app.min.js created: 45.2 kB → 12.8 kB (gzipped: 4.2 kB)
File build/app.min.js.map created (source map).

Done, without errors.

When using the 'gzip' report option, compression statistics include both minified and gzipped sizes for better insight into network transfer savings.