UglifyJS

repository·master·Indexed 11 days ago

https://github.com/mishoo/uglifyjs

A comprehensive JavaScript parser, mangler, compressor, and beautifier toolkit used to reduce file sizes for web deployment. Version 3.19.3 provides a CLI and a programmatic `minify()` API for optimizing JavaScript code, including support for source maps, property mangling, and dead code removal.

Tokens
7.8K
Snippets
33
Records
38
Agent score
94%

What's inside UglifyJS

  1. Handle quoted property names during mangling

    master

    By default, using a quoted property name (e.g., o["foo"]) reserves that name so it isn't mangled even if used unquoted (o.foo).

    • Use --mangle-props keep_quoted to ensure these names are preserved.
    • If the output will be processed by UglifyJS again, use -O keep_quoted_props to maintain consistency.
    uglifyjs stuff.js --mangle-props keep_quoted -c -m
  2. Create composed source maps from input maps

    master

    If you are compressing code that was already output by a compiler (like CoffeeScript), you can map back to the original source instead of the intermediate JS. Pass the existing source map using the content option within --source-map.

    • Use --source-map "content='/path/to/input/source.map'" for a file path.
    • Use --source-map "content=inline" if the source map is embedded inline with the source files.
    uglifyjs file.js --source-map "content='/path/to/input/source.map'"
  3. Enable Fast Minify Mode

    master

    If you want to speed up builds significantly, you can enable 'Fast Minify Mode' by disabling the compress step. This focuses only on whitespace removal and symbol mangling, which accounts for ~95% of size reduction in most cases. This can be 3 to 5 times faster than a full build.

    CLI: uglifyjs file.js -m (only mangling)

    API: UglifyJS.minify(code, { compress: false, mangle: true });

    uglifyjs file.js -m
  4. Use the UglifyJS CLI

    master

    The uglifyjs command allows you to minify, compress, and beautify JavaScript files from the terminal.

    Basic Syntax

    uglifyjs [input files] [options]

    Key Usage Rules

    • Multiple Files: You can pass multiple input files. UglifyJS parses them in sequence within the same global scope, allowing references between files to be resolved correctly.
    • Input Order: It is recommended to pass input files first, followed by options.
    • Separating Options and Files: If you prefer to pass options before the input files, use a double dash (--) to prevent the files from being interpreted as option arguments.
    • STDIN: If no input file is specified, UglifyJS reads from STDIN.
    • Output: By default, output is sent to STDOUT. Use the --output (-o) flag to specify a file path.
    uglifyjs [input files] [options]
    
    # Example with double dash to separate options from files
    uglifyjs --compress --mangle -- input.js
  5. Install UglifyJS

    master

    You can install UglifyJS via NPM either as a global command-line application or as a local dependency for programmatic use in your projects.

    Prerequisites

    • Ensure you have the latest version of node.js installed.

    Installation Commands

    • Global (CLI usage):
      npm install uglify-js -g
    • Local (Programmatic use):
      npm install uglify-js
    npm install uglify-js -g
  6. Configure Mangle options

    master

    The mangle configuration object controls the renaming of identifiers to reduce file size.

    Common settings:

    • reserved: An array of identifiers (e.g., ['foo', 'bar']) that must not be renamed.
    • toplevel: When true, allows mangling of names declared in the top-level scope.
    • eval: When true, mangles names visible in scopes where eval or with are used.

    Use the mangle object within the options passed to UglifyJS.minify().

    // Basic mangling with reserved names
    UglifyJS.minify(code, { mangle: { reserved: ['firstLongName'] } }).code;
    
    // Mangling top-level names
    UglifyJS.minify(code, { mangle: { toplevel: true } }).code;
  7. Configure Compress options

    master

    The compress configuration object controls various code optimization transformations. Most options are enabled by default (true).

    Key functional groups include:

    • Code Removal: dead_code (removes unreachable code), unused (drops unreferenced functions/variables), drop_console (discards console.* calls), and drop_debugger (removes debugger; statements).
    • Hoisting: hoist_exports (hoists export statements), hoist_funs (hoists function declarations), hoist_props (hoists properties from constant literals), and hoist_vars (hoists var declarations).
    • Inlining & Reduction: inline (controls function inlining levels), reduce_funcs (inlines single-use functions), and reduce_vars (optimizes constant assignments).
    • Unsafe Optimizations: Enabling unsafe allows transformations that might change behavior in edge cases, such as unsafe_math (optimizing numerical expressions which may affect floating point precision) or unsafe_proto (optimizing Array.prototype.slice.call(a) to [].slice.call(a)).
    • Side Effects: pure_funcs allows you to specify an array of function names that UglifyJS should assume have no side effects, enabling more aggressive dead code removal. Warning: Ensure symbols in pure_funcs are also in mangle.reserved to prevent mangling errors.
    // Example of using pure_funcs to allow dropping Math.floor calls if the result is unused
    UglifyJS.minify(code, { 
      compress: { 
        pure_funcs: [ 'Math.floor' ] 
      } 
    });
  8. Enable the unsafe compress option

    master

    The unsafe option in the compress configuration enables transformations that might break code logic in specific, contrived cases but generally reduce minified size for most standard code.

    Transformations include:

    • Converting new Array(1, 2, 3) or Array(1, 2, 3) to [1, 2, 3].
    • Converting new Object() to {}.
    • Converting String(exp) or exp.toString() to "" + exp.
    • Discarding the new keyword for Object, RegExp, Function, Error, and Array constructors.
  9. Configure Mangle Property names

    master

    The --mangle-props functionality (configured via mangle.properties) allows for the renaming of object property names.

    Available options:

    • regex: A RegExp literal to target only specific property names for mangling.
    • reserved: An array of property names that should not be mangled.
    • keep_quoted: If true, only unquoted property names are mangled.
    • debug: If set to an empty string "" or a non-empty string, it enables debugging by keeping the original name as a suffix.
    • builtins / domprops / globals: Boolean flags to allow/disallow mangling of built-in APIs, DOM properties, or global object properties. Use with caution.
  10. Basic usage of the UglifyJS CLI

    master

    The UglifyJS CLI is used to minify JavaScript files. By default, it reads files from the provided paths and outputs the minified code to STDOUT. You can specify an output file using the -o or --output flag.

    To minify a file and save it to a new file:

    uglifyjs input.js -o output.min.js

    To minify multiple files (the CLI supports simple globbing with * and ?):

    uglifyjs src/*.js -o bundle.min.js
  11. Debugging with Source Maps

    master

    Many compress transformations (simplification, rearrangement, inlining, removal) can make source map debugging difficult because the optimized code may no longer exist in a way that maps back to the original.

    Best Practice: For the highest fidelity in source map debugging, disable the compress option and use only mangle.

  12. Use native Uglify AST with minify()

    master

    You can use UglifyJS.minify() to work directly with Uglify's internal Abstract Syntax Tree (AST) instead of strings. This is useful for multi-stage transformations.

    Parse only (produce AST):

    var result = UglifyJS.minify(code, {
        parse: {},
        compress: false,
        mangle: false,
        output: {
            ast: true,
            code: false
        }
    });
    // result.ast contains the native Uglify AST

    Accept AST input (produce both AST and code):

    var result = UglifyJS.minify(ast, {
        compress: {},
        mangle: {},
        output: {
            ast: true,
            code: true
        }
    });
    // result.ast contains the native Uglify AST
    // result.code contains the minified code string
    var result = UglifyJS.minify(code, {
        parse: {},
        compress: false,
        mangle: false,
        output: {
            ast: true,
            code: false
        }
    });