### Advanced Minify Options Combination
Source: https://terser.org/docs/api-reference
Example showcasing a combination of `toplevel`, `compress` with `global_defs` and `passes`, and `format` with `preamble` options.
```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
},
format: {
preamble: "/* minified */"
}
};
var result = await minify(code, options);
console.log(result.code);
```
--------------------------------
### Error Handling Example
Source: https://terser.org/docs/api-reference
Illustrates how to handle potential errors during the minification process using a try-catch block.
```APIDOC
## Error Handling Example
### Description
Shows how to gracefully handle errors that may occur during the minification process by wrapping the `minify` call in a `try...catch` block.
### Code Example
```javascript
try {
const result = await minify({"foo.js" : "if (0) else console.log(1);"});
// Process the successful result
} catch (error) {
// Extract error details
const { message, filename, line, col, pos } = error;
console.error(`Minification failed: ${message} at ${filename}:${line}:${col}`);
// Handle the error appropriately
}
```
```
--------------------------------
### Advanced Minification Options
Source: https://terser.org/docs/api-reference
Shows an example of combining multiple advanced options like `toplevel`, `compress` with `global_defs` and `passes`, and `format` with `preamble`.
```APIDOC
## Advanced Minification Options
### Description
An example demonstrating the use of several advanced configuration options for `minify()`, including `toplevel`, `compress` (with `global_defs` and `passes`), and `format` (with `preamble`).
### Parameters
#### `options.toplevel` (boolean)
- If `true`, enables top-level scope optimization.
#### `options.compress` (object)
- Configuration for the compression phase.
- `global_defs` (object): Defines global variables that can be used for conditional compilation.
- `passes` (number): The number of compression passes to perform.
#### `options.format` (object)
- Configuration for the output format.
- `preamble` (string): A string to prepend to the minified output.
### Request Example
```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
},
format: {
preamble: "/* minified */"
}
};
var result = await minify(code, options);
console.log(result.code);
// /* minified */
// alert(10);
```
```
--------------------------------
### Terser Minification Examples
Source: https://terser.org/docs/options
Demonstrates Terser's minification capabilities with different mangle options. Use these examples to see how Terser renames variables and functions.
```javascript
var code = fs.readFileSync("test.js", "utf8");
await minify(code).code;
// 'function funcName(a,n){}var globalVar;'
```
```javascript
await minify(code, { mangle: { reserved: ['firstLongName'] } }).code;
// 'function funcName(firstLongName,a){}var globalVar;'
```
```javascript
await minify(code, { mangle: { toplevel: true } }).code;
// 'function n(n,a){}var a;'
```
--------------------------------
### Source Map Generation Example
Source: https://terser.org/docs/api-reference
Demonstrates how to generate a source map when minifying JavaScript code. The source map is returned in the `map` property of the result.
```APIDOC
## Source Map Options
To generate a source map:
```javascript
var result = await 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 (see the spec) in source map file.
You can set option `sourceMap.url` to be `"inline"` and source map will be appended to code.
You can also specify `sourceMap.root` property to be included in source map:
```javascript
var result = await minify({"file1.js": "var a = function() {};"}, {
sourceMap: {
root: "http://example.com/src",
url: "out.js.map"
}
});
```
If you're compressing compiled JavaScript and have a source map for it, you can use `sourceMap.content`:
```javascript
var result = await minify({"compiled.js": "compiled code"}, {
sourceMap: {
content: "content from compiled.js.map",
url: "minified.js.map"
}
});
// same as before, it returns `code` and `map`
```
If you're using the `X-SourceMap` header instead, you can just omit `sourceMap.url`.
If you happen to need the source map as a raw object, set `sourceMap.asObject` to `true`.
```
--------------------------------
### Persisting Name Cache
Source: https://terser.org/docs/api-reference
Provides an example of how to read, use, and write back a name cache to the file system for persistent mangling across application runs.
```APIDOC
## Persisting Name Cache
### Description
Demonstrates how to persist the `nameCache` to the file system. This allows the mangling of names to remain consistent between different executions of your application.
### Code Example
```javascript
const fs = require('fs');
var cacheFileName = "/tmp/cache.json";
var options = {
mangle: {
properties: true,
},
// Load cache from file, or use empty object if file doesn't exist
nameCache: fs.existsSync(cacheFileName) ? JSON.parse(fs.readFileSync(cacheFileName, "utf8")) : {}
};
// Process and write part 1
fs.writeFileSync("part1.js", await minify({
"file1.js": fs.readFileSync("file1.js", "utf8"),
"file2.js": fs.readFileSync("file2.js", "utf8")
}, options).code, "utf8");
// Process and write part 2
fs.writeFileSync("part2.js", await minify({
"file3.js": fs.readFileSync("file3.js", "utf8"),
"file4.js": fs.readFileSync("file4.js", "utf8")
}, options).code, "utf8");
// Save the updated cache back to the file
fs.writeFileSync(cacheFileName, JSON.stringify(options.nameCache), "utf8");
```
```
--------------------------------
### Original JavaScript Code for `keep_quoted` Example
Source: https://terser.org/docs/cli-usage
This JavaScript code demonstrates the use of both quoted and unquoted property access, which is relevant for the `keep_quoted` option.
```javascript
// stuff.js
var o = {
"foo": 1,
bar: 3
};
o.foo += o.bar;
console.log(o.foo);
```
--------------------------------
### Original JavaScript Code for Property Mangling Example
Source: https://terser.org/docs/cli-usage
This is the source JavaScript code that will be processed by Terser for property name mangling.
```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());
```
--------------------------------
### Example of Debug-Mangled JavaScript Code
Source: https://terser.org/docs/cli-usage
This JavaScript code demonstrates how properties are mangled when using the `debug` option for property name mangling. The original `o.foo` and `o.bar` are transformed into `o._$foo$_` and `o._$bar$_`.
```javascript
var o={_$foo$_:1,_$bar$_:3};o._$foo$_+=o._$bar$_,console.log(o._$foo$_);
```
--------------------------------
### Retain Copyright Comments with Terser
Source: https://terser.org/docs/miscellaneous
Use the `--comments` option to keep specific comments. By default, it preserves comments starting with '!' and JSDoc comments with specific tags. Use `--comments all` to keep all comments or a regex to filter them. Note that comments attached to discarded code might be lost.
```bash
--comments
--comments all
--comments /^!/
```
--------------------------------
### JavaScript Function with Preserve Comment
Source: https://terser.org/docs/miscellaneous
This example shows a JavaScript function where a JSDoc comment with '@preserve' is intended to be kept. However, if the inner function is not referenced, the comment might be lost.
```javascript
function f() {
/** @preserve Foo Bar */
function g() {
// this function is never called
}
return something();
}
```
--------------------------------
### Custom Suffix for Debug Property Name Mangling
Source: https://terser.org/docs/cli-usage
Pass a custom suffix to `--mangle-props debug` to further customize mangled property names, for example, `--mangle-props debug=XYZ`. This can help in tracking how properties are mangled across different compilations.
```bash
--mangle-props debug=XYZ
```
--------------------------------
### Persisting Name Cache to File System
Source: https://terser.org/docs/api-reference
Demonstrates how to read a name cache from a file, use it during minification, and write the updated cache back to the file.
```javascript
var cacheFileName = "/tmp/cache.json";
var options = {
mangle: {
properties: true,
},
nameCache: JSON.parse(fs.readFileSync(cacheFileName, "utf8"))
};
fs.writeFileSync("part1.js", await minify({
"file1.js": fs.readFileSync("file1.js", "utf8"),
"file2.js": fs.readFileSync("file2.js", "utf8")
}, options).code, "utf8");
fs.writeFileSync("part2.js", await 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");
```
--------------------------------
### Using `toplevel` Option
Source: https://terser.org/docs/api-reference
Demonstrates how to use the `toplevel` option to control top-level variable and function scope during minification.
```APIDOC
## Using `toplevel` Option
### Description
Configure minification behavior with the `toplevel` option. When set to `true`, top-level variables and functions are not modified.
### Parameters
#### `options.toplevel` (boolean)
- If `true`, enables top-level scope optimization.
### Request Example
```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 };
var result = await minify(code, options);
console.log(result.code);
// console.log(3+7);
```
```
--------------------------------
### Generate Source Map with Filename and URL
Source: https://terser.org/docs/api-reference
Demonstrates how to generate a source map for minified output. The `filename` option sets the output file name, and `url` specifies the source map URL comment in the minified code.
```javascript
var result = await 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
```
--------------------------------
### Browser Loading
Source: https://terser.org/docs/api-reference
Shows how to include Terser in a web page using CDN links, making the `minify` function available globally.
```APIDOC
## Browser Loading
### Description
Load Terser in a web browser by including script tags from a CDN. This exposes a global `Terser` object with a `.minify` property.
### Code Example
```html
```
```
--------------------------------
### Using `nameCache` Option
Source: https://terser.org/docs/api-reference
Illustrates the use of `nameCache` to persist and reuse variable name mappings across multiple minification runs.
```APIDOC
## Using `nameCache` Option
### Description
Utilize the `nameCache` option to maintain consistent variable name mangling across different minification operations, which is useful for incremental builds or multiple file processing.
### Parameters
#### `options.mangle` (object)
- Configuration for name mangling.
- `toplevel` (boolean): If `true`, enables top-level scope optimization.
#### `options.nameCache` (object)
- An object used for caching generated names. It should be initialized as an empty object `{}` or loaded from a previous cache.
### Request Example
```javascript
var options = {
mangle: {
toplevel: true,
},
nameCache: {}
};
var result1 = await minify({
"file1.js": "function add(first, second) { return first + second; }"
}, options);
var result2 = await minify({
"file2.js": "console.log(add(1 + 2, 3 + 4));"
}, options);
console.log(result1.code);
// function n(n,r){return n+r}
console.log(result2.code);
// console.log(n(3,7));
```
```
--------------------------------
### Error Handling in Minification
Source: https://terser.org/docs/api-reference
Demonstrates how to use a try-catch block to handle potential errors during the minification process, extracting error details.
```javascript
try {
const result = await minify({"foo.js" : "if (0) else console.log(1);"});
// Do something with result
} catch (error) {
const { message, filename, line, col, pos } = error;
// Do something with error
}
```
--------------------------------
### Enable Compression with Terser CLI
Source: https://terser.org/docs/cli-usage
Use the --compress or -c flag to enable JavaScript compression. You can pass a comma-separated list of compression options, where a bare option name enables it and 'option=value' sets a specific value.
```bash
terser file.js -c toplevel,sequences=false
```
--------------------------------
### Generate Source Map with Root URL
Source: https://terser.org/docs/api-reference
Shows how to specify a `root` URL for the source map, which is included in the source map file. This is useful for setting the base path for source files.
```javascript
var result = await minify({"file1.js": "var a = function() {};"}, {
sourceMap: {
root: "http://example.com/src",
url: "out.js.map"
}
});
```
--------------------------------
### Importing Terser in Node.js
Source: https://terser.org/docs/api-reference
Demonstrates how to import the `minify` function from the Terser library in a Node.js environment using CommonJS or ES Modules.
```APIDOC
## Importing Terser in Node.js
### Description
Import the `minify` function from the Terser library for use in Node.js applications.
### Code Examples
#### Using CommonJS:
```javascript
const { minify } = require("terser");
```
#### Using ES Modules:
```javascript
import { minify } from "terser";
```
```
--------------------------------
### Separating Options and Input Files
Source: https://terser.org/docs/cli-usage
Use a double dash (--) to ensure options are processed before input files, preventing misinterpretation of file names as options.
```bash
terser --compress --mangle -- input.js
```
--------------------------------
### Generate Source Map with Terser CLI
Source: https://terser.org/docs/cli-usage
Pass --source-map and --output options to generate a source map file alongside the compressed JavaScript. Additional options can specify the source map's filename, root URL, and its own URL.
```bash
terser 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 Structure
Source: https://terser.org/docs/api-reference
Illustrates the structure of the configuration object for Terser's minify function, showing nested options for parsing, compression, mangling, and formatting.
```javascript
{
parse: {
// parse options
},
compress: {
// compress options
},
mangle: {
// mangle options
properties: {
// mangle property options
}
},
format: {
// format options (can also use `output` for backwards compatibility)
},
sourceMap: {
// source map options
},
ecma: 5, // specify one of: 5, 2015, 2016, etc.
enclose: false, // or specify true, or "args:values"
keep_classnames: false,
keep_fnames: false,
ie8: false,
module: false,
nameCache: null, // or specify a name cache object
safari10: false,
toplevel: false
}
```
--------------------------------
### Include Define File for Terser Build
Source: https://terser.org/docs/miscellaneous
Define global constants in a separate JavaScript file and include it in the Terser build command. Terser recognizes these constants and performs optimizations accordingly.
```javascript
var DEBUG = false;
var PRODUCTION = true;
// etc.
```
```bash
terser build/defines.js js/foo.js js/bar.js... -c
```
--------------------------------
### Load Terser in the Browser
Source: https://terser.org/docs/api-reference
Include Terser via CDN in your HTML to make the `Terser.minify` function available globally.
```html
```
--------------------------------
### Synchronous Minification
Source: https://terser.org/docs/api-reference
Introduces the `minify_sync()` function as an alternative to the asynchronous `minify()` for immediate return values.
```APIDOC
## Synchronous Minification
### Description
Provides a synchronous alternative, `minify_sync()`, to the primary asynchronous `minify()` function. This version returns the result immediately without using promises or async/await.
### Method
`minify_sync(code, options)`
### Parameters
#### `code` (string | object)
- The JavaScript code to minify, either as a single string or an object of multiple files.
#### `options` (object, optional)
- Configuration options for minification.
### Usage
```javascript
// Example usage (assuming Terser is loaded)
// var result = minify_sync(code, options);
```
```
--------------------------------
### Combine Mangle Properties Options
Source: https://terser.org/docs/cli-usage
This command demonstrates combining the `regex` and `reserved` options for `--mangle-props` to achieve more specific property name mangling.
```bash
$ terser example.js -c passes=2 -m --mangle-props regex=/_$/,reserved=[bar_]
```
--------------------------------
### Load Terser using NPM
Source: https://terser.org/docs/api-reference
Import the `minify` function from the Terser package for use in your Node.js application.
```javascript
const { minify } = require("terser");
```
```javascript
import { minify } from "terser";
```
--------------------------------
### Basic Minification (Async)
Source: https://terser.org/docs/api-reference
Performs minification on a single JavaScript string using the asynchronous `minify` function with default options.
```APIDOC
## Basic Minification (Async)
### Description
Minify a single JavaScript code string using the asynchronous `minify` function. By default, `compress` and `mangle` are enabled.
### Method
`async minify(code, options)`
### Parameters
#### `code` (string)
- The JavaScript code to minify.
#### `options` (object, optional)
- Configuration options for minification.
### Request Example
```javascript
var code = "function add(first, second) { return first + second; }";
var result = await minify(code, { sourceMap: true });
console.log(result.code); // minified output: function add(n,d){return n+d}
console.log(result.map); // source map
```
```
--------------------------------
### Minify Multiple JavaScript Files
Source: https://terser.org/docs/api-reference
Pass an object to `minify` where keys are filenames and values are source code strings to minify multiple files at once.
```javascript
var code = {
"file1.js": "function add(first, second) { return first + second; }",
"file2.js": "console.log(add(1 + 2, 3 + 4));"
};
var result = await minify(code);
console.log(result.code);
```
--------------------------------
### Enabling Fast Minify Mode via CLI
Source: https://terser.org/docs/miscellaneous
Use the -m flag in the Terser CLI to enable fast minify mode, which disables compression for significantly faster builds.
```bash
terser file.js -m
```
--------------------------------
### Basic Terser CLI Invocation
Source: https://terser.org/docs/cli-usage
The fundamental structure for using Terser. Input files are typically listed before options.
```bash
terser [input files] [options]
```
--------------------------------
### Minifying Multiple Files (Async)
Source: https://terser.org/docs/api-reference
Minifies multiple JavaScript files simultaneously by passing an object where keys are filenames and values are source code.
```APIDOC
## Minifying Multiple Files (Async)
### Description
Minify multiple JavaScript files at once by providing an object where keys are filenames and values are the corresponding source code.
### Method
`async minify(code, options)`
### Parameters
#### `code` (object)
- An object where keys are filenames (e.g., `"file1.js"`) and values are the JavaScript source code strings.
### Request Example
```javascript
var code = {
"file1.js": "function add(first, second) { return first + second; }",
"file2.js": "console.log(add(1 + 2, 3 + 4));"
};
var result = await minify(code);
console.log(result.code);
// function add(d,n){return d+n}console.log(add(3,7));
```
```
--------------------------------
### Clean and Reinstall Dependencies with Yarn
Source: https://terser.org/docs/miscellaneous
After updating `package.json`, run these commands to remove existing `node_modules` and `yarn.lock` files, and then reinstall all packages to apply the `terser` alias.
```bash
$ rm -rf node_modules yarn.lock
$ yarn
```
--------------------------------
### Toplevel Option for Minification
Source: https://terser.org/docs/api-reference
Use the `toplevel: true` option to enable top-level scope optimization during minification.
```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 };
var result = await minify(code, options);
console.log(result.code);
```
--------------------------------
### Basic Minification with Source Maps
Source: https://terser.org/docs/api-reference
Use the `minify` function to minify a single JavaScript string. Enables source map generation by default.
```javascript
var code = "function add(first, second) { return first + second; }";
var result = await minify(code, { sourceMap: true });
console.log(result.code);
console.log(result.map);
```
--------------------------------
### Using Name Cache for Consistent Mangling Across Files
Source: https://terser.org/docs/cli-usage
This sequence of commands shows how to use `--name-cache` to ensure consistent mangled property names when processing multiple files in separate calls. It involves removing an existing cache file and then using the same cache file for subsequent Terser runs.
```bash
$ rm -f /tmp/cache.json # start fresh
$ terser file1.js file2.js --mangle-props --name-cache /tmp/cache.json -o part1.js
$ terser file3.js file4.js --mangle-props --name-cache /tmp/cache.json -o part2.js
```
--------------------------------
### Minify Function Options
Source: https://terser.org/docs/api-reference
This section outlines the available options for the `minify` function, which control how JavaScript code is processed.
```APIDOC
## Minify Options
This section outlines the available options for the `minify` function, which control how JavaScript code is processed.
### Options:
* `ecma` (default `undefined`): Specify ECMAScript version (e.g., `5`, `2015`, `2016`) to override `compress` and `format`'s `ecma` options.
* `enclose` (default `false`): Embed output in a function. Can be `true` or a string like `"args[:values]"`.
* `parse` (default `{}`): Object for specifying additional parse options.
* `compress` (default `{}`): Set to `false` to skip compression. Pass an object for custom compress options.
* `mangle` (default `true`): Set to `false` to skip mangling names. Pass an object for custom mangle options.
* `mangle.properties` (default `false`): Subcategory of `mangle` for custom mangle property options.
* `module` (default `false`): Use when minifying an ES6 module. Implies `"use strict"` and enables top-scope name mangling. Enables `toplevel` if `compress` or `mangle` are enabled.
* `format` or `output` (default `null`): Object for specifying additional format options. Defaults are optimized for compression.
* `sourceMap` (default `false`): Pass an object to specify source map options.
* `toplevel` (default `false`): Enable top-level variable/function name mangling and drop unused variables/functions.
* `nameCache` (default `null`): Pass an empty object `{}` or a previously used `nameCache` object to cache mangled names across multiple `minify()` calls. This is a read/write property.
* `ie8` (default `false`): Set to `true` to support IE8.
* `keep_classnames` (default: `undefined`): Set to `true` to prevent discarding or mangling class names. Pass a regex to only keep matching class names. If `undefined`, it inherits from `keep_fnames`.
* `keep_fnames` (default: `false`): Set to `true` to prevent discarding or mangling function names. Pass a regex to only keep matching function names. Useful for `Function.prototype.name`.
* `safari10` (default: `false`): Set to `true` to work around Safari 10/11 bugs in loop scoping and `await`.
```
--------------------------------
### Set TERSER_DEBUG_DIR Environment Variable (Bash)
Source: https://terser.org/docs/reporting-issues
Use this command to set the TERSER_DEBUG_DIR environment variable in bash to log input code and options for each minify() call.
```bash
TERSER_DEBUG_DIR=/tmp/terser-log-dir command-that-uses-terser
ls /tmp/terser-log-dir
terser-debug-123456.log
```
--------------------------------
### Enabling Fast Minify Mode via API
Source: https://terser.org/docs/miscellaneous
Configure Terser's API to use fast minify mode by setting 'compress' to false in the options object.
```javascript
await minify(code, { compress: false, mangle: true });
```
--------------------------------
### Using Terser with SpiderMonkey AST Input
Source: https://terser.org/docs/miscellaneous
Process JavaScript code represented as a SpiderMonkey AST (JSON) by piping it to Terser with the -p spidermonkey option.
```bash
acorn file.js | terser -p spidermonkey -m -c
```
--------------------------------
### Terser with Option Overrides
Source: https://terser.org/docs/cli-usage
Pass specific compression options as a comma-separated list to modify Terser's behavior.
```bash
terser input.js --compress ecma=2015,computed_props=false
```
--------------------------------
### Name Cache for Consistent Mangling
Source: https://terser.org/docs/api-reference
Utilize the `nameCache` option to ensure consistent variable and function name mangling across multiple minification runs.
```javascript
var options = {
mangle: {
toplevel: true,
},
nameCache: {}
};
var result1 = await minify({
"file1.js": "function add(first, second) { return first + second; }"
}, options);
var result2 = await minify({
"file2.js": "console.log(add(1 + 2, 3 + 4));"
}, options);
console.log(result1.code);
console.log(result2.code);
```
--------------------------------
### Generate Source Map with Content from Existing Map
Source: https://terser.org/docs/api-reference
Enables source map generation by providing the `content` option with the source map of the input JavaScript. This is useful when minifying already compiled and mapped code.
```javascript
var result = await minify({"compiled.js": "compiled code"}, {
sourceMap: {
content: "content from compiled.js.map",
url: "minified.js.map"
}
});
// same as before, it returns `code` and `map`
```
--------------------------------
### Enable Mangling with Terser CLI
Source: https://terser.org/docs/cli-usage
To enable name mangling, use the --mangle or -m flag. Options like 'toplevel' and 'eval' can be passed as comma-separated values to control the scope of mangling.
```bash
terser ... -m toplevel,eval
```
--------------------------------
### Enable Source Map Generation in Terser CLI
Source: https://terser.org/docs/cli-usage
To enable source map generation, use the --source-map option. Specify the content of the source map using 'content=' followed by a file path or 'inline' for embedded source maps.
```bash
terser --source-map "content='/path/to/input/source.map'"
```
```bash
terser --source-map "content=inline"
```
--------------------------------
### Mangle All Properties (Unsafe)
Source: https://terser.org/docs/cli-usage
This command enables mangling for all properties, excluding built-in JavaScript properties. This is highly unsafe and likely to break your code.
```bash
$ terser example.js -c passes=2 -m --mangle-props
```
--------------------------------
### Basic JavaScript Code for Mangling
Source: https://terser.org/docs/options
This is the input JavaScript code that will be processed by Terser.
```javascript
// test.js
var globalVar;
function funcName(firstLongName, anotherLongName) {
var myVariable = firstLongName + anotherLongName;
}
```
--------------------------------
### Terser Annotations for Function Inlining and Purity
Source: https://terser.org/docs/miscellaneous
Use annotations like /*@__INLINE__*/, /*#__NOINLINE__*/, and /*#__PURE__*/ to control function inlining and mark calls as pure for potential removal.
```javascript
/*@__INLINE__*/
function_always_inlined_here()
/*#__NOINLINE__*/
function_cant_be_inlined_into_here()
const x = /*#__PURE__*/i_am_dropped_if_x_is_not_used()
function lookup(object, key) { return object[key]; }
lookup({ i_will_be_mangled_too: "bar" }, /*@__KEY__*/ "i_will_be_mangled_too");
```
--------------------------------
### Alias Uglify-ES to Terser in package.json
Source: https://terser.org/docs/miscellaneous
Add this `resolutions` block to your `package.json` to force `yarn` to use `terser` whenever `uglify-es` is a dependency.
```json
"resolutions": {
"uglify-es": "npm:terser"
}
```
--------------------------------
### Enable Property Name Mangling with Regex
Source: https://terser.org/docs/cli-usage
Use this command to mangle properties ending with an underscore, suitable for internal methods. Be aware that property name mangling can break your code.
```bash
terser example.js -c -m --mangle-props regex=/_$/
```
--------------------------------
### Conditional Compilation with --define
Source: https://terser.org/docs/miscellaneous
Use the `--define` flag to declare global constants for Terser. This enables dead code removal for blocks dependent on these constants. Nested constants can be specified using dot notation.
```bash
--define DEBUG=false
--define env.DEBUG=false
```
--------------------------------
### Conditional Compilation via Terser API
Source: https://terser.org/docs/miscellaneous
Configure conditional compilation using the `global_defs` option within the `compress` object in the Terser programmatic API. Set `dead_code` to `true` to enable dead code removal.
```javascript
var result = await minify(fs.readFileSync("input.js", "utf8"), {
compress: {
dead_code: true,
global_defs: {
DEBUG: false
}
}
});
```
--------------------------------
### Mangle All Properties Except Reserved
Source: https://terser.org/docs/cli-usage
This command mangles all properties except those explicitly listed in the `reserved` array. This is still considered unsafe.
```bash
$ terser example.js -c passes=2 -m --mangle-props reserved=[foo_,bar_]
```
--------------------------------
### Set TERSER_DEBUG_DIR Environment Variable (cross-env)
Source: https://terser.org/docs/reporting-issues
Use npx cross-env to set the TERSER_DEBUG_DIR environment variable if you are unsure how to set it directly in your shell.
```bash
> npx cross-env TERSER_DEBUG_DIR=/path/to/logs command-that-uses-terser
```
--------------------------------
### Enable `keep_quoted` Option for Property Mangling
Source: https://terser.org/docs/cli-usage
Use this command to enable the `keep_quoted` option, which prevents mangling of property names that are accessed using bracket notation with quotes.
```bash
$ terser stuff.js --mangle-props keep_quoted -c -m
```
--------------------------------
### Result of Combined Mangle Properties Options
Source: https://terser.org/docs/cli-usage
The output code reflecting the combined effect of regex-based and reserved property name mangling.
```javascript
var x={o:3,t:1,calc:function(){return this.t+this.o},bar_:2};console.log(x.calc());
```
--------------------------------
### Result of Mangling All Properties
Source: https://terser.org/docs/cli-usage
The output code after Terser mangles all properties, demonstrating the transformation of original property names.
```javascript
var x={o:3,t:1,i:function(){return this.t+this.o},s:2};console.log(x.i());
```
--------------------------------
### Mangle Properties Matching Regex
Source: https://terser.org/docs/cli-usage
This command mangles properties that match the provided regular expression. While less unsafe than mangling all properties, it still carries risks.
```bash
$ terser example.js -c passes=2 -m --mangle-props regex=/_$/
```
--------------------------------
### Terser Reading from STDIN
Source: https://terser.org/docs/cli-usage
When no input files are provided, Terser reads JavaScript code from standard input.
```bash
terser
```
--------------------------------
### Debug Property Name Mangling with Terser CLI
Source: https://terser.org/docs/cli-usage
Use the `--mangle-props debug` option to mangle property names while keeping them somewhat readable for debugging purposes. This helps identify issues caused by mangling in large codebases.
```bash
$ terser stuff.js --mangle-props debug -c -m
```
--------------------------------
### Result of Mangling Except Reserved Properties
Source: https://terser.org/docs/cli-usage
The output code where specified properties are preserved while others are mangled.
```javascript
var x={o:3,foo_:1,t:function(){return this.foo_+this.o},bar_:2};console.log(x.t());
```
--------------------------------
### Result of Mangling Properties Matching Regex
Source: https://terser.org/docs/cli-usage
The output code where only properties matching the regex pattern have been mangled.
```javascript
var x={o:3,t:1,calc:function(){return this.t+this.o},i:2};console.log(x.calc());
```
--------------------------------
### Reserve Names from Mangling in Terser CLI
Source: https://terser.org/docs/cli-usage
Prevent specific names from being mangled by using the --mangle reserved option with a comma-separated list of names to protect.
```bash
terser ... -m reserved=['$','require','exports']
```
--------------------------------
### Replace Identifier with Expression using API
Source: https://terser.org/docs/miscellaneous
To replace an identifier with a non-constant expression, prefix the `global_defs` key with '@'. This instructs Terser to parse the value as an expression, not a string literal.
```javascript
await minify("alert('hello');", {
compress: {
global_defs: {
"@alert": "console.log"
}
}
}).code;
// returns: 'console.log("hello");'
```
--------------------------------
### Replace Identifier with String Literal using API
Source: https://terser.org/docs/miscellaneous
If the `global_defs` key is not prefixed with '@', Terser treats the value as a string literal. This can lead to unexpected results if an expression was intended.
```javascript
await minify("alert('hello');", {
compress: {
global_defs: {
"alert": "console.log"
}
}
}).code;
// returns: '"console.log"("hello");'
```
--------------------------------
### Result of Mangling with `keep_quoted`
Source: https://terser.org/docs/cli-usage
The output code after applying Terser with the `keep_quoted` option, showing that quoted property names are preserved.
```javascript
var o={foo:1,o:3};o.foo+=o.o,console.log(o.foo);
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.