### Load UglifyJS Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Initializes the UglifyJS library after installation via NPM. ```javascript var UglifyJS = require("uglify-js"); ``` -------------------------------- ### Install UglifyJS via NPM Source: https://context7.com/mishoo/uglifyjs/llms.txt Use these commands to install the package globally for CLI access or locally for project dependencies. ```bash # Install globally for command-line usage npm install uglify-js -g # Install locally for programmatic use npm install uglify-js ``` -------------------------------- ### Install UglifyJS Globally Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Install UglifyJS globally using NPM for command-line application use. ```bash npm install uglify-js -g ``` -------------------------------- ### Install UglifyJS Programmatically Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Install UglifyJS using NPM for programmatic use within your projects. ```bash npm install uglify-js ``` -------------------------------- ### Minify Options Structure Example Source: https://github.com/mishoo/uglifyjs/blob/master/README.md An example of how the minify options object can be structured. ```APIDOC ## Minify Options Structure ```javascript { parse: { // parse options }, compress: { // compress options }, mangle: { // mangle options properties: { // mangle property options } }, output: { // output options }, sourceMap: { // source map options }, nameCache: null, // or specify a name cache object toplevel: false, warnings: false, } ``` ``` -------------------------------- ### Source Map Options - Basic Usage Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of generating a source map with filename and URL. ```APIDOC ### Source Map Options To generate a source map: ```javascript var result = UglifyJS.minify({"file1.js": "var a = function() {};"}, { sourceMap: { filename: "out.js", url: "out.js.map" } }); console.log(result.code); // minified output console.log(result.map); // source map ``` Note that the source map is not saved in a file, it's just returned in `result.map`. The value passed for `sourceMap.url` is only used to set `//# sourceMappingURL=out.js.map` in `result.code`. The value of `filename` is only used to set `file` attribute in source map file. ``` -------------------------------- ### Source Map Options - Source Root Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of specifying a `sourceRoot` for the source map. ```APIDOC You can also specify `sourceRoot` property to be included in source map: ```javascript var result = UglifyJS.minify({"file1.js": "var a = function() {};"}, { sourceMap: { root: "http://example.com/src", url: "out.js.map" } }); ``` ``` -------------------------------- ### Apply UglifyJS mangle options Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Examples showing how to use UglifyJS.minify with different mangle configurations. ```javascript var code = fs.readFileSync("test.js", "utf8"); UglifyJS.minify(code).code; // 'function funcName(a,n){}var globalVar;' UglifyJS.minify(code, { mangle: { reserved: ['firstLongName'] } }).code; // 'function funcName(firstLongName,a){}var globalVar;' UglifyJS.minify(code, { mangle: { toplevel: true } }).code; // 'function n(n,a){}var a;' ``` -------------------------------- ### Input JavaScript for Property Mangling Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example source file used to demonstrate property mangling effects. ```javascript // example.js var x = { baz_: 0, foo_: 1, calc: function() { return this.foo_ + this.baz_; } }; x.bar_ = 2; x["baz_"] = 3; console.log(x.calc()); ``` -------------------------------- ### Optimize prototype method calls Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of unsafe prototype optimization. ```javascript Array.prototype.slice.call(a) ``` -------------------------------- ### Optimize numeric comparisons Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of unsafe numeric comparison optimization. ```javascript a <= b ``` -------------------------------- ### Compress typeof expressions Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of how typeof expressions are optimized into more compact forms. ```javascript typeof foo == "undefined" → void 0 === foo ``` -------------------------------- ### Source Map Options - Content Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of providing the content of a source map for minifying already compiled JavaScript. ```APIDOC If you're compressing compiled JavaScript and have a source map for it, you can use `sourceMap.content`: ```javascript var result = UglifyJS.minify({"compiled.js": "compiled code"}, { sourceMap: { content: "content from compiled.js.map", url: "minified.js.map" } }); // same as before, it returns `code` and `map` ``` ``` -------------------------------- ### Compact template literals Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of how template literal compression transforms expressions into string literals. ```javascript `foo ${42}` → "foo 42" ``` -------------------------------- ### Source Map Options - Inline Source Map Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of embedding the source map directly into the output code. ```APIDOC You can set option `sourceMap.url` to be `"inline"` and source map will be appended to code. ``` -------------------------------- ### Optimize numerical expressions Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of unsafe math optimization that may result in imprecise floating point values. ```javascript 2 * x * 3 ``` -------------------------------- ### Catch Block Reference Error Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of a ReferenceError in older environments that UglifyJS might suppress. ```javascript var a; try { throw 42; } catch ({ [a]: b, // ReferenceError: a is not defined }) { let a; } ``` -------------------------------- ### Default Parameter Reference Error Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of a ReferenceError occurring within a default parameter function scope. ```javascript console.log(((a, b = function() { return a; // ReferenceError: a is not defined }()) => b)()); ``` -------------------------------- ### Source Map Options - Names Omission Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of omitting symbol names from the source map to reduce file size. ```APIDOC If you wish to reduce file size of the source map, set option `sourceMap.names` to be `false` and all symbol names will be omitted. ``` -------------------------------- ### Execute UglifyJS via Command Line Source: https://context7.com/mishoo/uglifyjs/llms.txt Use the CLI for build automation, minification, and source map generation. ```bash # Basic minification uglifyjs input.js -o output.js # Compress and mangle uglifyjs input.js -c -m -o output.min.js # Multiple input files (combined in order) uglifyjs file1.js file2.js file3.js -o bundle.min.js -c -m # Generate source map uglifyjs input.js -o output.min.js -c -m --source-map "url='output.min.js.map'" # Source map with source content included uglifyjs input.js -o output.min.js -c -m \ --source-map "url='output.min.js.map',includeSources=true" # Composed source map (from transpiled code) uglifyjs compiled.js -o output.min.js -c -m \ --source-map "content='compiled.js.map',url='output.min.js.map'" # Read from stdin, write to stdout cat input.js | uglifyjs -c -m # Beautify instead of minify uglifyjs input.js -b -o formatted.js # Custom compress options uglifyjs input.js -c drop_console=true,passes=2 -o output.min.js ``` -------------------------------- ### Enable Compression with Options Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Pass '--compress' or '-c' to enable the JavaScript compressor. Options can be provided as a comma-separated list, e.g., 'toplevel,sequences=false'. ```bash uglifyjs file.js -c toplevel,sequences=false ``` -------------------------------- ### Input AST, Output Code and AST Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Provide a native Uglify AST as input to 'minify()' and configure 'output.ast: true' and 'output.code: true' to receive both the minified code and the resulting AST. ```javascript // example: accept native Uglify AST input and then compress and mangle // to produce both code and native AST. var result = UglifyJS.minify(ast, { compress: {}, mangle: {}, output: { ast: true, code: true // optional - faster if false } }); // result.ast contains native Uglify AST // result.code contains the minified code in string form. ``` -------------------------------- ### Use Configuration File for Minification Source: https://context7.com/mishoo/uglifyjs/llms.txt This command demonstrates how to use a JSON configuration file to minify JavaScript files, applying all specified options from the config. ```bash uglifyjs src/*.js --config-file uglify.config.json -o dist/bundle.min.js ``` -------------------------------- ### UglifyJS CLI Options Source: https://github.com/mishoo/uglifyjs/blob/master/README.md A reference of available command-line flags for configuring the UglifyJS minification process. ```APIDOC ## CLI Options ### Description Configuration flags for the UglifyJS command-line tool. ### Parameters - **--ie** (flag) - Support non-standard Internet Explorer. - **--keep-fargs** (flag) - Do not mangle/drop function arguments. - **--keep-fnames** (flag) - Do not mangle/drop function names. - **--module** (flag) - Process input as ES module. - **--no-module** (flag) - Avoid optimizations which may alter runtime behavior. - **--name-cache ** (string) - File to hold mangled name mappings. - **--self** (flag) - Build UglifyJS as a library. - **--source-map [options]** (object) - Enable source map/specify source map options (base, content, filename, includeSources, names, root, url). - **--timings** (flag) - Display operations run time on STDERR. - **--toplevel** (flag) - Compress and/or mangle variables in top level scope. - **--v8** (flag) - Support non-standard Chrome & Node.js. - **--verbose** (flag) - Print diagnostic messages. - **--warn** (flag) - Print warning messages. - **--webkit** (flag) - Support non-standard Safari/Webkit. - **--wrap ** (string) - Embed everything in a big function. - **--output / -o ** (string) - Declare the output file. ``` -------------------------------- ### Command Line Usage Source: https://context7.com/mishoo/uglifyjs/llms.txt Use UglifyJS from the command line for build scripts and automation. Supports multiple input files, configuration files, and all minification options. ```APIDOC ## Command Line Usage Use UglifyJS from the command line for build scripts and automation. Supports multiple input files, configuration files, and all minification options. ### Basic Minification ```bash uglifyjs input.js -o output.js ``` ### Compress and Mangle ```bash uglifyjs input.js -c -m -o output.min.js ``` ### Multiple Input Files ```bash uglifyjs file1.js file2.js file3.js -o bundle.min.js -c -m ``` ### Generate Source Map ```bash uglifyjs input.js -o output.min.js -c -m --source-map "url='output.min.js.map'" ``` ### Source Map with Source Content ```bash uglifyjs input.js -o output.min.js -c -m \ --source-map "url='output.min.js.map',includeSources=true" ``` ### Composed Source Map ```bash uglifyjs compiled.js -o output.min.js -c -m \ --source-map "content='compiled.js.map',url='output.min.js.map'" ``` ### Read from Stdin, Write to Stdout ```bash cat input.js | uglifyjs -c -m ``` ### Beautify Instead of Minify ```bash uglifyjs input.js -b -o formatted.js ``` ### Custom Compress Options ```bash uglifyjs input.js -c drop_console=true,passes=2 -o output.min.js ``` ``` -------------------------------- ### Reserved Word Usage Error Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of a SyntaxError when using a reserved word as a variable name. ```javascript var await; class A { static p = await; } // SyntaxError: Unexpected reserved word ``` -------------------------------- ### Catch Block Loop Identifier Conflict Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of a SyntaxError when reusing a catch variable in a loop. ```javascript try {} catch (e) { for (var e of []); } // SyntaxError: Identifier 'e' has already been declared ``` -------------------------------- ### Invalid Unicode Escape Sequence Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of a SyntaxError triggered by an invalid Unicode escape sequence. ```javascript console.log(String.raw`\uFo`); // SyntaxError: Invalid Unicode escape sequence ``` -------------------------------- ### Read Options from JSON Config File Source: https://context7.com/mishoo/uglifyjs/llms.txt Specify minification options using a JSON configuration file with the --config-file flag. This is recommended for complex build configurations. ```bash uglifyjs input.js --config-file uglify.config.json -o output.min.js ``` -------------------------------- ### Show Timing Information Source: https://context7.com/mishoo/uglifyjs/llms.txt Enable the --timings flag to display detailed timing information for different stages of the minification process. This helps in identifying performance bottlenecks. ```bash uglifyjs input.js -c -m --timings -o output.min.js ``` -------------------------------- ### BigInt Arithmetic TypeError Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of a TypeError when attempting to perform arithmetic between BigInt and number types. ```javascript 1n + 1; // TypeError: can't convert BigInt to number ``` -------------------------------- ### Catch Block Identifier Redeclaration Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of a SyntaxError when a variable is redeclared within a catch block. ```javascript try { // ... } catch ({ message: a }) { var a; } // SyntaxError: Identifier 'a' has already been declared ``` -------------------------------- ### UglifyJS CLI Options Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Overview of the command line interface options for UglifyJS. ```APIDOC ## UglifyJS CLI Options ### Description Command line flags to control the minification, parsing, and output formatting of JavaScript files. ### Parameters #### Options - **-h, --help** (flag) - Print usage information. - **-V, --version** (flag) - Print version number. - **-p, --parse** (options) - Specify parser options (acorn, bare_returns, spidermonkey). - **-c, --compress** (options) - Enable compressor or specify compressor options (e.g., pure_funcs). - **-m, --mangle** (options) - Mangle names or specify mangler options (e.g., reserved). - **--mangle-props** (options) - Mangle properties (builtins, debug, domprops, globals, keep_quoted, regex, reserved). - **-b, --beautify** (options) - Beautify output or specify output options (preamble, quote_style, wrap_iife). - **-O, --output-opts** (options) - Specify output options. - **-o, --output** (file) - Output file path (default STDOUT). - **--annotations** (flag) - Process and preserve comment annotations. - **--no-annotations** (flag) - Ignore and discard comment annotations. - **--comments** (filter) - Preserve copyright comments (all, or JS RegExp). - **--config-file** (file) - Read minify options from JSON file. - **-d, --define** (expr) - Global definitions. - **-e, --enclose** (arg) - Embed everything in a big function. - **--expression** (flag) - Parse a single expression, rather than a program. ``` -------------------------------- ### Identifier Redeclaration Syntax Error Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of a SyntaxError caused by redeclaring an identifier in a block scope. ```javascript a => { let a; }; // SyntaxError: Identifier 'a' has already been declared ``` -------------------------------- ### Persist NameCache to File System Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Demonstrates how to read and write a name cache to a JSON file to maintain mangling consistency across separate build processes. ```javascript var cacheFileName = "/tmp/cache.json"; var options = { mangle: { properties: true, }, nameCache: JSON.parse(fs.readFileSync(cacheFileName, "utf8")) }; fs.writeFileSync("part1.js", UglifyJS.minify({ "file1.js": fs.readFileSync("file1.js", "utf8"), "file2.js": fs.readFileSync("file2.js", "utf8") }, options).code, "utf8"); fs.writeFileSync("part2.js", UglifyJS.minify({ "file3.js": fs.readFileSync("file3.js", "utf8"), "file4.js": fs.readFileSync("file4.js", "utf8") }, options).code, "utf8"); fs.writeFileSync(cacheFileName, JSON.stringify(options.nameCache), "utf8"); ``` -------------------------------- ### UglifyJS Command Line with Options Before Input Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Use a double dash to separate options from input files when options are provided before the input files. ```bash uglifyjs --compress --mangle -- input.js ``` -------------------------------- ### UglifyJS Command Line Usage Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Basic command-line usage for UglifyJS, specifying input files and options. ```bash uglifyjs [input files] [options] ``` -------------------------------- ### Enable Fast Minify Mode via CLI Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Use the -m flag to enable symbol mangling while keeping compression disabled for faster build times. ```bash uglifyjs file.js -m ``` -------------------------------- ### Compress Options Configuration Source: https://github.com/mishoo/uglifyjs/blob/master/README.md A comprehensive list of available options to configure the UglifyJS compressor. ```APIDOC ## Compress Options ### Description Configuration settings to control the code compression process in UglifyJS. ### Parameters - **annotations** (boolean) - Default: true - Drop functions marked as pure. - **arguments** (boolean) - Default: true - Replace arguments[index] with parameter names. - **arrows** (boolean) - Default: true - Optimize arrow functions. - **assignments** (boolean) - Default: true - Optimize assignment expressions. - **awaits** (boolean) - Default: true - Optimize await expressions. - **booleans** (boolean) - Default: true - Optimize boolean contexts. - **collapse_vars** (boolean) - Default: true - Collapse single-use non-constant variables. - **comparisons** (boolean) - Default: true - Optimize binary nodes. - **conditionals** (boolean) - Default: true - Optimize if and conditional expressions. - **dead_code** (boolean) - Default: true - Remove unreachable code. - **default_values** (boolean) - Default: true - Drop overshadowed default values. - **directives** (boolean) - Default: true - Remove redundant directives. - **drop_console** (boolean) - Default: false - Discard console.* function calls. - **drop_debugger** (boolean) - Default: true - Remove debugger statements. - **evaluate** (boolean|string|number) - Default: true - Evaluate expressions for constant representation. - **expression** (boolean) - Default: false - Preserve completion values from terminal statements. - **functions** (boolean) - Default: true - Convert var declarations to function declarations. - **global_defs** (object) - Default: {} - Conditional compilation definitions. - **hoist_exports** (boolean) - Default: true - Hoist export statements. - **hoist_funs** (boolean) - Default: false - Hoist function declarations. - **hoist_props** (boolean) - Default: true - Hoist properties from constant literals. - **hoist_vars** (boolean) - Default: false - Hoist var declarations. - **if_return** (boolean) - Default: true - Optimize if/return and if/continue. - **imports** (boolean) - Default: true - Drop unreferenced import symbols. - **inline** (boolean|number) - Default: true - Inline function calls. - **join_vars** (boolean) - Default: true - Join consecutive var statements. - **keep_fargs** (boolean) - Default: false - Retain unused function arguments. - **keep_infinity** (boolean) - Default: false - Prevent Infinity compression. - **loops** (boolean) - Default: true - Optimize loops. - **merge_vars** (boolean) - Default: true - Combine and reuse variables. - **module** (boolean) - Default: false - Process input as ES module. - **negate_iife** (boolean) - Default: true - Negate IIFEs. - **objects** (boolean) - Default: true - Compact duplicate keys in object literals. - **passes** (number) - Default: 1 - Number of compression passes. - **properties** (boolean) - Default: true - Rewrite property access to dot notation. - **pure_funcs** (array) - Default: null - List of functions to treat as pure. ``` -------------------------------- ### Using SpiderMonkey AST with UglifyJS Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Import and process SpiderMonkey-compatible ASTs using the `-p spidermonkey` option. ```APIDOC ## ESTree / SpiderMonkey AST Integration ### Description UglifyJS can import and process SpiderMonkey-compatible ASTs, typically generated by parsers like Acorn. ### Usage Use the `-p spidermonkey` option to indicate that the input is a SpiderMonkey AST in JSON format. ```bash acorn file.js | uglifyjs -p spidermonkey -m -c ``` ### Process When this option is used, UglifyJS bypasses its own parser and instead transforms the provided SpiderMonkey AST into its internal AST format before proceeding with compression and mangling. ``` -------------------------------- ### Source Map Options - X-SourceMap Header Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Note on using the X-SourceMap header instead of sourceMap.url. ```APIDOC If you're using the `X-SourceMap` header instead, you can just omit `sourceMap.url`. ``` -------------------------------- ### Example of comment loss due to tree shaking Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Comments attached to nodes that are removed by the compressor will not appear in the final output. ```javascript function f() { /** @preserve Foo Bar */ function g() { // this function is never called } return something(); } ``` -------------------------------- ### Output Configuration Options Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Defines the configuration object structure for controlling UglifyJS output behavior. ```APIDOC ## Output Configuration Options ### Description These options control how the code generator formats the output. By default, it produces the shortest code possible, but these settings allow for beautification and specific formatting requirements. ### Request Body - **annotations** (boolean) - Optional - Retain comment annotations like /*@__PURE__*/. - **ascii_only** (boolean) - Optional - Escape Unicode characters in strings and regexps. - **beautify** (boolean) - Optional - Whether to beautify the output. - **braces** (boolean) - Optional - Always insert braces in control statements. - **comments** (boolean/string/regexp) - Optional - Preserve specific comments. - **extendscript** (boolean) - Optional - Enable workarounds for Adobe ExtendScript bugs. - **galio** (boolean) - Optional - Enable workarounds for ANT Galio bugs. - **indent_level** (number/string) - Optional - Indent level (spaces or string). - **indent_start** (number/string) - Optional - Prefix all lines with whitespace. - **inline_script** (boolean) - Optional - Escape HTML comments and slashes in . - **keep_quoted_props** (boolean) - Optional - Prevent stripping quotes from property names. - **max_line_len** (number) - Optional - Maximum line length. - **preamble** (string) - Optional - Text to prepend to the output. - **preserve_line** (boolean) - Optional - Retain line numbering. - **quote_keys** (boolean) - Optional - Quote all keys in literal objects. - **quote_style** (number) - Optional - Preferred quote style (0: double, 1: single, 2: double, 3: original). - **semicolons** (boolean) - Optional - Separate statements with semicolons. - **shebang** (boolean) - Optional - Preserve shebang in preamble. - **width** (number) - Optional - Line width for beautification. - **wrap_iife** (boolean) - Optional - Wrap immediately invoked function expressions. ``` -------------------------------- ### Spread Syntax Property Incorrect Result Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Example of incorrect object property behavior when using spread syntax in certain environments. ```javascript console.log({ ...{ set 42(v) {}, 42: "PASS", }, }); // Expected: { '42': 'PASS' } // Actual: { '42': undefined } ``` -------------------------------- ### Working with AST using minify() Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Control AST generation and input/output when using the `minify` function. ```APIDOC ## Using Native Uglify AST with `minify()` ### Description Control whether the `minify` function produces or accepts native Uglify AST. ### Parse Only (Output AST) To parse code and produce only the native Uglify AST, set `ast: true` and `code: false` in the `output` configuration. ```javascript var UglifyJS = require('uglify-js'); var result = UglifyJS.minify(code, { parse: {}, compress: false, mangle: false, output: { ast: true, code: false // optional - faster if false } }); // result.ast contains native Uglify AST ``` ### Accept AST Input (Input AST) To accept native Uglify AST as input and then compress and mangle it, pass the AST object directly to `minify`. ```javascript var UglifyJS = require('uglify-js'); var result = UglifyJS.minify(ast, { compress: {}, mangle: {}, output: { ast: true, code: true // optional - faster if false } }); // result.ast contains native Uglify AST // result.code contains the minified code in string form. ``` ``` -------------------------------- ### CLI Fast Mode Source: https://context7.com/mishoo/uglifyjs/llms.txt Execute UglifyJS from the command line in fast mode by using the -m flag (mangle) and omitting the -c flag (compress). This prioritizes build speed over maximum size reduction. ```bash uglifyjs input.js -m -o output.min.js ``` -------------------------------- ### Mangle Properties Matching Regex in UglifyJS Source: https://context7.com/mishoo/uglifyjs/llms.txt Mangle only property names that match a specified regular expression. This allows selective mangling, for example, only properties ending with an underscore. ```javascript var UglifyJS = require("uglify-js"); var code = ` var x = { baz_: 0, foo_: 1, calc: function() { return this.foo_ + this.baz_; } }; x.bar_ = 2; console.log(x.calc()); `; // Mangle only properties matching a regex var result = UglifyJS.minify(code, { mangle: { properties: { regex: /_$/ // Only mangle properties ending with _ } } }); console.log(result.code); ``` -------------------------------- ### Preserve Copyright Comments Source: https://context7.com/mishoo/uglifyjs/llms.txt Use the --comments flag with a regular expression to preserve specific comments, such as copyright notices. The /^!/ pattern targets comments starting with '!'. ```bash uglifyjs input.js -c -m --comments /^!/ -o output.min.js ``` -------------------------------- ### Advanced Minify Options Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Combines multiple configuration options including global definitions, compression passes, and output preambles. ```javascript var code = { "file1.js": "function add(first, second) { return first + second; }", "file2.js": "console.log(add(1 + 2, 3 + 4));" }; var options = { toplevel: true, compress: { global_defs: { "@console.log": "alert" }, passes: 2 }, output: { beautify: false, preamble: "/* uglified */" } }; var result = UglifyJS.minify(code, options); console.log(result.code); // /* uglified */ // alert(10);" ``` -------------------------------- ### Generate Source Map with Filename and URL Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Configure source map generation by providing a filename for the output and a URL for the source map. The `sourceMap.url` option sets the `//# sourceMappingURL` comment in the minified code. ```javascript var result = UglifyJS.minify({"file1.js": "var a = function() {};"}, { sourceMap: { filename: "out.js", url: "out.js.map" } }); console.log(result.code); // minified output console.log(result.map); // source map ``` -------------------------------- ### Conditional Compilation with --define Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Use the --define switch to declare global variables that UglifyJS will treat as constants, enabling dead code removal. For example, defining DEBUG=false will discard code within if (DEBUG) blocks. ```bash uglifyjs build/defines.js js/foo.js js/bar.js... -c ``` -------------------------------- ### Generate Source Map with UglifyJS Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Pass --source-map and --output to generate a source map file. The source map will be written to a file with a .map extension. ```bash uglifyjs js/file1.js js/file2.js \ -o foo.min.js -c -m \ --source-map "root='http://foo.com/src',url='foo.min.js.map'" ``` -------------------------------- ### Minify Options Overview Source: https://github.com/mishoo/uglifyjs/blob/master/README.md A comprehensive list of options that can be passed to the UglifyJS.minify() function to control the minification process. ```APIDOC ## Minify Options - `annotations` — (boolean) Pass `false` to ignore all comment annotations and elide them from output. Pass `true` to both compress and retain comment annotations. - `compress` (object | boolean) — Defaults to `{}`. Pass `false` to skip compressing entirely. Pass an object to specify custom compress options. - `expression` (boolean) — Defaults to `false`. Parse as a single expression, e.g. JSON. - `ie` (boolean) — Defaults to `false`. Enable workarounds for Internet Explorer bugs. - `keep_fargs` (boolean) — Defaults to `false`. Prevent discarding or mangling of function arguments. - `keep_fnames` (boolean) — Defaults to `false`. Prevent discarding or mangling of function names. Useful for code relying on `Function.prototype.name`. - `mangle` (object | boolean) — Defaults to `true`. Pass `false` to skip mangling names, or pass an object to specify mangle options. - `mangle.properties` (object | boolean) — Defaults to `false`. A subcategory of the mangle option. Pass an object to specify custom mangle property options. - `module` (boolean) — Defaults to `true`. Process input as ES module, enabling implicit `"use strict";` and support for top-level `await`. When explicitly specified, also enables `toplevel`. - `nameCache` (object | null) — Defaults to `null`. Pass an empty object `{}` or a previously used `nameCache` object to cache mangled variable and property names across multiple invocations of `minify()`. - `output` (object | null) — Defaults to `null`. Pass an object to specify additional output options. The defaults are optimized for best compression. - `parse` (object) — Defaults to `{}`. Pass an object to specify additional parse options. - `sourceMap` (object | boolean) — Defaults to `false`. Pass an object to specify source map options. - `toplevel` (boolean) — Defaults to `false`. Set to `true` to enable top level variable and function name mangling and to drop unused variables and functions. - `v8` (boolean) — Defaults to `false`. Enable workarounds for Chrome & Node.js bugs. - `warnings` (boolean | string) — Defaults to `false`. Pass `true` to return compressor warnings in `result.warnings`. Use the value `"verbose"` for more detailed warnings. - `webkit` (boolean) — Defaults to `false`. Enable workarounds for Safari/WebKit bugs. PhantomJS users should set this option to `true`. ``` -------------------------------- ### Configure UglifyJS Output Formatting Source: https://context7.com/mishoo/uglifyjs/llms.txt Control indentation, comment preservation, and quote styles during minification. ```javascript var UglifyJS = require("uglify-js"); var code = "function add(a,b){return a+b}var x=add(1,2);"; // Beautify output var result = UglifyJS.minify(code, { output: { beautify: true, indent_level: 2 } }); console.log(result.code); // Preserve specific comments var codeWithComments = ` /*! Copyright 2024 */ /** @license MIT */ // Regular comment function test() { return 42; } `; // Keep license/copyright comments var result = UglifyJS.minify(codeWithComments, { output: { comments: "some" // Keeps @license, @preserve, @cc_on } }); // Keep all comments var result = UglifyJS.minify(codeWithComments, { output: { comments: "all" } }); // Keep comments matching regex var result = UglifyJS.minify(codeWithComments, { output: { comments: /^!/ // Keep comments starting with ! } }); // Add preamble (e.g., license header) var result = UglifyJS.minify(code, { output: { preamble: "/* minified with UglifyJS */" } }); console.log(result.code); // "/* minified with UglifyJS */\nfunction add..." // Quote style options var objCode = 'var x = { "foo": 1, bar: 2 };'; var result = UglifyJS.minify(objCode, { output: { quote_style: 1 // 0=auto, 1=single, 2=double, 3=original } }); ``` -------------------------------- ### Mangle All Properties Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Demonstrates mangling all properties except built-in JavaScript properties. ```bash $ uglifyjs example.js -c -m --mangle-props ``` ```javascript var x={o:0,_:1,l:function(){return this._+this.o}};x.t=2,x.o=3,console.log(x.l()); ``` -------------------------------- ### Process as ES Module Source: https://context7.com/mishoo/uglifyjs/llms.txt Use the --module flag to process the input file as an ES module. This enables specific optimizations relevant to module structures. ```bash uglifyjs input.js -c -m --module -o output.min.js ``` -------------------------------- ### Compress Options Source: https://context7.com/mishoo/uglifyjs/llms.txt Configuration options for the UglifyJS compressor to control code transformations. ```APIDOC ## Compress Options ### Description Configure the compressor to control code transformations including dead code removal, constant folding, and function inlining. ### Parameters - **compress** (object|boolean) - Optional - An object with specific compression settings or false to disable compression. ### Common Options - **global_defs** (object) - Definitions for conditional compilation. - **dead_code** (boolean) - Remove unreachable code. - **unused** (boolean) - Remove unused variables and functions. - **drop_console** (boolean) - Remove console statements. - **pure_funcs** (array) - List of functions that can be safely removed if the result is unused. ### Request Example ```javascript var result = UglifyJS.minify(code, { compress: { global_defs: { DEBUG: false }, drop_console: true } }); ``` ``` -------------------------------- ### Specify Source Map Root URL Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Use the 'root' option within --source-map to provide the URL where original source files can be found. This helps in reconstructing the original file paths. ```bash --source-map "root=''" ``` -------------------------------- ### Implement a compressor feature Source: https://github.com/mishoo/uglifyjs/blob/master/CONTRIBUTING.md Use this pattern to define a transformation rule for an AST node. Ensure the compressor options are checked before returning a modified node. ```javascript OPT(AST_Debugger, function(self, compressor) { if (compressor.option("drop_debugger")) return make_node(AST_EmptyStatement, self); return self; }); ``` -------------------------------- ### Compose Source Map with Input Source Map Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Pass '--source-map "content=/path/to/input/source.map"' to use an existing source map for composing a new one. Use 'content=inline' if the source map is embedded. ```bash --source-map "content='/path/to/input/source.map'" ``` ```bash --source-map "content=inline" ``` -------------------------------- ### UglifyJS JSON Configuration File Source: https://context7.com/mishoo/uglifyjs/llms.txt A JSON configuration file allows for detailed specification of UglifyJS options, including compression, mangling, output formatting, and source map settings. This is useful for complex build processes. ```json { "compress": { "dead_code": true, "drop_console": true, "drop_debugger": true, "global_defs": { "DEBUG": false, "@console.log": "void 0" }, "passes": 2, "pure_funcs": ["console.info"] }, "mangle": { "toplevel": true, "reserved": ["$", "require", "exports"] }, "output": { "comments": "some", "preamble": "/* Copyright 2024 */" }, "sourceMap": { "filename": "output.js", "url": "output.js.map", "includeSources": true } } ``` -------------------------------- ### Output Options (Beautify) Source: https://context7.com/mishoo/uglifyjs/llms.txt Control code formatting and output style including indentation, quote style, semicolons, and comment preservation. ```APIDOC ## Output Options (Beautify) Control code formatting and output style including indentation, quote style, semicolons, and comment preservation. ### Beautify Output ```javascript var UglifyJS = require("uglify-js"); var code = "function add(a,b){return a+b}var x=add(1,2);"; // Beautify output var result = UglifyJS.minify(code, { output: { beautify: true, indent_level: 2 } }); console.log(result.code); ``` ### Preserve Specific Comments ```javascript var codeWithComments = ` /*! Copyright 2024 */ /** @license MIT */ // Regular comment function test() { return 42; } `; // Keep license/copyright comments var result = UglifyJS.minify(codeWithComments, { output: { comments: "some" // Keeps @license, @preserve, @cc_on } }); // Keep all comments var result = UglifyJS.minify(codeWithComments, { output: { comments: "all" } }); // Keep comments matching regex var result = UglifyJS.minify(codeWithComments, { output: { comments: /^!/ // Keep comments starting with ! } }); ``` ### Add Preamble ```javascript // Add preamble (e.g., license header) var result = UglifyJS.minify(code, { output: { preamble: "/* minified with UglifyJS */" } }); console.log(result.code); // "/* minified with UglifyJS */\nfunction add..." ``` ### Quote Style Options ```javascript var objCode = 'var x = { "foo": 1, bar: 2 };'; var result = UglifyJS.minify(objCode, { output: { quote_style: 1 // 0=auto, 1=single, 2=double, 3=original } }); ``` ``` -------------------------------- ### Configure Compressor Options Source: https://context7.com/mishoo/uglifyjs/llms.txt Control code transformations like dead code removal, constant folding, and function inlining using the compress object. ```javascript var UglifyJS = require("uglify-js"); var code = ` var DEBUG = true; function unused() { return 42; } if (DEBUG) { console.log("debug mode"); } var result = 1 + 2 + 3; `; // Compress with global definitions for conditional compilation var result = UglifyJS.minify(code, { compress: { global_defs: { DEBUG: false }, dead_code: true, unused: true, passes: 2 } }); console.log(result.code); // Dead code and unused function removed // Drop console statements in production var result = UglifyJS.minify("console.log('debug'); alert('hello');", { compress: { drop_console: true } }); console.log(result.code); // "alert('hello');" // Replace function calls using global_defs with @ prefix var result = UglifyJS.minify("alert('hello');", { compress: { global_defs: { "@alert": "console.log" } } }); console.log(result.code); // 'console.log("hello");' // Specify pure functions for better dead code elimination var result = UglifyJS.minify("var x = Math.floor(a/b);", { compress: { pure_funcs: ["Math.floor"], unused: true, toplevel: true } }); console.log(result.code); // "" (entire statement removed) ``` -------------------------------- ### Handle Errors Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Shows how to capture and handle errors returned by the minify function, as it does not throw exceptions by default. ```javascript var result = UglifyJS.minify({"foo.js" : "if (0) else console.log(1);"}); console.log(JSON.stringify(result.error)); // {"message":"Unexpected token: keyword (else)","filename":"foo.js","line":1,"col":7,"pos":7} ``` ```javascript var result = UglifyJS.minify(code, options); if (result.error) throw result.error; ``` -------------------------------- ### Define a compression test case Source: https://github.com/mishoo/uglifyjs/blob/master/CONTRIBUTING.md Define test cases by specifying the compressor options, the input code, and the expected output code. ```javascript drop_debugger: { options = { drop_debugger: true, } input: { debugger; if (foo) debugger; } expect: { if (foo); } } ``` -------------------------------- ### Using SpiderMonkey AST Input Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Process input files described in SpiderMonkey AST JSON format by using the '-p spidermonkey' option. UglifyJS will convert this AST to its internal format before further processing. ```bash acorn file.js | uglifyjs -p spidermonkey -m -c ``` -------------------------------- ### Basic Source Map Generation in UglifyJS Source: https://context7.com/mishoo/uglifyjs/llms.txt Generate a basic source map for debugging minified code. The `sourceMap.filename` option specifies the output filename, and `sourceMap.url` provides the URL for the source map file. ```javascript var UglifyJS = require("uglify-js"); // Basic source map generation var result = UglifyJS.minify({ "file1.js": "var a = function() {};" }, { sourceMap: { filename: "out.js", url: "out.js.map" } }); console.log(result.code); // Minified code with //# sourceMappingURL=out.js.map console.log(result.map); // Source map JSON string ``` -------------------------------- ### Enable Verbose Warnings Source: https://context7.com/mishoo/uglifyjs/llms.txt Use the --warn and --verbose flags to enable more detailed warning messages during the minification process. This can help in diagnosing potential issues. ```bash uglifyjs input.js -c -m --warn --verbose -o output.min.js ``` -------------------------------- ### Fast Minify Mode (Node.js) Source: https://context7.com/mishoo/uglifyjs/llms.txt Use the UglifyJS.minify function in Node.js with 'compress: false' and 'mangle: true' for a faster build that only performs mangling, skipping compression. This offers a good balance for development builds. ```javascript var UglifyJS = require("uglify-js"); // Fast mode: mangle only, no compression var result = UglifyJS.minify(code, { compress: false, mangle: true }); ``` -------------------------------- ### Specifying Pure Functions to Drop Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Provide an array of function names to `pure_funcs` to specify which function calls should be considered pure and potentially dropped if their return value is unused. ```javascript ['myPureFunction', 'anotherOne'] ``` -------------------------------- ### Use Name Cache for Consistent Mangling Source: https://context7.com/mishoo/uglifyjs/llms.txt Employ the --name-cache option with a file path to ensure consistent mangling across multiple build steps or code-split bundles. This is essential for maintaining inter-file references. ```bash uglifyjs part1.js -c -m --name-cache /tmp/cache.json -o part1.min.js ``` ```bash uglifyjs part2.js -c -m --name-cache /tmp/cache.json -o part2.min.js ``` -------------------------------- ### Define source code for mangling Source: https://github.com/mishoo/uglifyjs/blob/master/README.md The sample JavaScript code used to demonstrate mangling behavior. ```javascript // test.js var globalVar; function funcName(firstLongName, anotherLongName) { var myVariable = firstLongName + anotherLongName; } ``` -------------------------------- ### Specify Source Map URL Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Use the 'url' option within --source-map to specify the URL where the source map can be found. If omitted, UglifyJS assumes HTTP X-SourceMap is used. ```bash --source-map "url=''" ``` -------------------------------- ### Optimizing If/Return Statements Source: https://github.com/mishoo/uglifyjs/blob/master/README.md The `if_return` option enables optimizations for `if`/`return` and `if`/`continue` statements. ```javascript if (condition) { return value; } ``` -------------------------------- ### Minify Multiple Files Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Minifies multiple files by passing an object where keys are filenames and values are source code. ```javascript var code = { "file1.js": "function add(first, second) { return first + second; }", "file2.js": "console.log(add(1 + 2, 3 + 4));" }; var result = UglifyJS.minify(code); console.log(result.code); // function add(d,n){return d+n}console.log(add(3,7)); ``` -------------------------------- ### AST Traversal and Transformation Source: https://github.com/mishoo/uglifyjs/blob/master/README.md Utilize `TreeWalker` and `TreeTransformer` for manipulating the UglifyJS AST. ```APIDOC ## Working with Uglify AST ### Description Perform transversal and transformation on the native Uglify AST using provided utilities. ### Tools - [`TreeWalker`](https://github.com/mishoo/UglifyJS/blob/master/lib/ast.js): For AST traversal. - [`TreeTransformer`](https://github.com/mishoo/UglifyJS/blob/master/lib/transform.js): For AST transformation. ```