Grunt plugin that minifies JavaScript files using UglifyJS with comprehensive options and source map support
npx @tessl/cli install tessl/npm-grunt-contrib-uglify@5.2.0Grunt 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.
npm install grunt-contrib-uglify --save-dev// In your Gruntfile.js
grunt.loadNpmTasks('grunt-contrib-uglify');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 uglifygrunt-contrib-uglify consists of two main components:
tasks/uglify.js): Registers the 'uglify' Grunt multi-task and handles file processing, options validation, and result reportingtasks/lib/uglify.js): Wraps UglifyJS functionality with Grunt-specific features like file handling, source maps, and name cachingThe plugin integrates with Grunt's file configuration system, supports glob patterns, and provides detailed compression statistics.
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;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 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;
}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;
}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;
}Simple file minification with default options:
grunt.initConfig({
uglify: {
my_target: {
files: {
'dest/output.min.js': ['src/input.js']
}
}
}
});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']
}
}
}
});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']
}
}
}
});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']
}
}
}
});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']
}
}
}
});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']
}
}
}
});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"]
}The plugin provides detailed error reporting for common issues:
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.jsThe 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.