Options
Parse options
-
bare_returns(defaultfalse) -- support top levelreturnstatements -
html5_comments(defaulttrue) -
shebang(defaulttrue) -- support#!commandas the first line -
spidermonkey(defaultfalse) -- accept a Spidermonkey (Mozilla) AST
Compress options
-
defaults(default:true) -- Passfalseto disable most default enabledcompresstransforms. Useful when you only want to enable a fewcompressoptions while disabling the rest. -
arrows(default:true) -- Class and object literal methods are converted will also be converted to arrow expressions if the resultant code is shorter:m(){return x}becomesm:()=>x. To do this to regular ES5 functions which don't usethisorarguments, seeunsafe_arrows. -
arguments(default:false) -- replacearguments[index]with function parameter name whenever possible. -
booleans(default:true) -- various optimizations for boolean context, for example!!a ? b : c → a ? b : c -
booleans_as_integers(default:false) -- Turn booleans into 0 and 1, also makes comparisons with booleans use==and!=instead of===and!==. -
collapse_vars(default:true) -- Collapse single-use non-constant variables, side effects permitting. -
comparisons(default:true) -- apply certain optimizations to binary nodes, e.g.!(a <= b) → a > b(only whenunsafe_comps), attempts to negate binary nodes, e.g.a = !b && !c && !d && !e → a=!(b||c||d||e)etc. Note:comparisonsworks best withlhs_constantsenabled. -
computed_props(default:true) -- Transforms constant computed properties into regular ones:{["computed"]: 1}is converted to{computed: 1}. -
conditionals(default:true) -- apply optimizations forif-s and conditional expressions -
dead_code(default:true) -- remove unreachable code -
directives(default:true) -- remove redundant or non-standard directives -
drop_console(default:false) -- Passtrueto discard calls toconsole.*functions. If you only want to discard a portion of console, you can pass an array like this['log', 'info'], which will only discardconsole.log、console.info. -
drop_debugger(default:true) -- removedebugger;statements -
ecma(default:5) -- Pass2015or greater to enablecompressoptions that will transform ES5 code into smaller ES6+ equivalent forms. -
evaluate(default:true) -- attempt to evaluate constant expressions -
expression(default:false) -- Passtrueto preserve completion values from terminal statements withoutreturn, e.g. in bookmarklets. -
global_defs(default:{}) -- see conditional compilation -
hoist_funs(default:false) -- hoist function declarations -
hoist_props(default:true) -- hoist properties from constant object and array literals into regular variables subject to a set of constraints. For example:var o={p:1, q:2}; f(o.p, o.q);is converted tof(1, 2);. Note:hoist_propsworks best withmangleenabled, thecompressoptionpassesset to2or higher, and thecompressoptiontoplevelenabled. -
hoist_vars(default:false) -- hoistvardeclarations (this isfalseby default because it seems to increase the size of the output in general) -
if_return(default:true) -- optimizations for if/return and if/continue -
inline(default:true) -- inline calls to function with simple/returnstatement:false-- same as00-- disabled inlining1-- inline simple functions2-- inline functions with arguments3-- inline functions with arguments and variablestrue-- same as3
-
join_vars(default:true) -- join consecutivevar,letandconststatements -
keep_classnames(default:false) -- Passtrueto prevent the compressor from discarding class names. Pass a regular expression to only keep class names matching that regex. See also: thekeep_classnamesmangle option. -
keep_fargs(default:true) -- Prevents the compressor from discarding unused function arguments. You need this for code which relies onFunction.length. -
keep_fnames(default:false) -- Passtrueto prevent the compressor from discarding function names. Pass a regular expression to only keep function names matching that regex. Useful for code relying onFunction.prototype.name. See also: thekeep_fnamesmangle option. -
keep_infinity(default:false) -- Passtrueto preventInfinityfrom being compressed into1/0, which may cause performance issues on Chrome. -
lhs_constants(default:true) -- Moves constant values to the left-hand side of binary nodes.foo == 42 → 42 == foo -
loops(default:true) -- optimizations fordo,whileandforloops when we can statically determine the condition. -
module(defaultfalse) -- Passtruewhen compressing an ES6 module. Strict mode is implied and thetopleveloption as well. -
negate_iife(default:true) -- negate "Immediately-Called Function Expressions" where the return value is discarded, to avoid the parens that the code generator would insert. -
passes(default:1) -- The maximum number of times to run compress. In some cases more than one pass leads to further compressed code. Keep in mind more passes will take more time. -
properties(default:true) -- rewrite property access using the dot notation, for examplefoo["bar"] → foo.bar -
pure_funcs(default:null) -- You can pass an array of names and Terser will assume that those functions do not produce side effects. DANGER: will not check if the name is redefined in scope. An example case here, for instancevar q = Math.floor(a/b). If variableqis not used elsewhere, Terser will drop it, but will still keep theMath.floor(a/b), not knowing what it does. You can passpure_funcs: [ 'Math.floor' ]to let it know that this function won't produce any side effect, in which case the whole statement would get discarded. The current implementation adds some overhead (compression will be slower). -
pure_getters(default:"strict") -- If you passtruefor this, Terser will assume that object property access (e.g.foo.barorfoo["bar"]) doesn't have any side effects. Specify"strict"to treatfoo.baras side-effect-free only whenfoois certain to not throw, i.e. notnullorundefined. -
pure_new(default:false) -- Set totrueto assumenew X()never has side effects. -
reduce_vars(default:true) -- Improve optimization on variables assigned with and used as constant values. -
reduce_funcs(default:true) -- Inline single-use functions when possible. Depends onreduce_varsbeing enabled. Disabling this option sometimes improves performance of the output code. -
sequences(default:true) -- join consecutive simple statements using the comma operator. May be set to a positive integer to specify the maximum number of consecutive comma sequences that will be generated. If this option is set totruethen the defaultsequenceslimit is200. Set option tofalseor0to disable. The smallestsequenceslength is2. Asequencesvalue of1is grandfathered to be equivalent totrueand as such means200. On rare occasions the default sequences limit leads to very slow compress times in which case a value of20or less is recommended. -
side_effects(default:true) -- Remove expressions which have no side effects and whose results aren't used. -
switches(default:true) -- de-duplicate and remove unreachableswitchbranches -
toplevel(default:false) -- drop unreferenced functions ("funcs") and/or variables ("vars") in the top level scope (falseby default,trueto drop both unreferenced functions and variables) -
top_retain(default:null) -- prevent specific toplevel functions and variables fromunusedremoval (can be array, comma-separated, RegExp or function. Impliestoplevel) -
typeofs(default:true) -- Transformstypeof foo == "undefined"intofoo === void 0. Note: recommend to set this value tofalsefor IE10 and earlier versions due to known issues. -
unsafe(default:false) -- apply "unsafe" transformations (details). -
unsafe_arrows(default:false) -- Convert ES5 style anonymous function expressions to arrow functions if the function body does not referencethis. Note: it is not always safe to perform this conversion if code relies on the the function having aprototype, which arrow functions lack. This transform requires that theecmacompress option is set to2015or greater. -
unsafe_comps(default:false) -- Reverse<and<=to>and>=to allow improved compression. This might be unsafe when an at least one of two operands is an object with computed values due the use of methods likeget, orvalueOf. This could cause change in execution order after operands in the comparison are switching. Or if one of two operands isNaN, the result is alwaysfalse. Compression only works if bothcomparisonsandunsafe_compsare both set to true. -
unsafe_Function(default:false) -- compress and mangleFunction(args, code)when bothargsandcodeare string literals. -
unsafe_math(default:false) -- optimize numerical expressions like2 * x * 3into6 * x, which may give imprecise floating point results. -
unsafe_symbols(default:false) -- removes keys from native Symbol declarations, e.gSymbol("kDog")becomesSymbol(). -
unsafe_methods(default: false) -- Converts{ m: function(){} }to{ m(){} }.ecmamust be set to6or greater to enable this transform. Ifunsafe_methodsis a RegExp then key/value pairs with keys matching the RegExp will be converted to concise methods. Note: if enabled there is a risk of getting a "<method name>is not a constructor" TypeError should any code try tonewthe former function. -
unsafe_proto(default:false) -- optimize expressions likeArray.prototype.slice.call(a)into[].slice.call(a) -
unsafe_regexp(default:false) -- enable substitutions of variables withRegExpvalues the same way as if they are constants. -
unsafe_undefined(default:false) -- substitutevoid 0if there is a variable namedundefinedin scope (variable name will be mangled, typically reduced to a single character) -
unused(default:true) -- drop unreferenced functions and variables (simple direct variable assignments do not count as references unless set to"keep_assign")
Mangle options
-
eval(defaultfalse) -- Passtrueto mangle names visible in scopes whereevalorwithare used. -
keep_classnames(defaultfalse) -- Passtrueto not mangle class names. Pass a regular expression to only keep class names matching that regex. See also: thekeep_classnamescompress option. -
keep_fnames(defaultfalse) -- Passtrueto not mangle function names. Pass a regular expression to only keep function names matching that regex. Useful for code relying onFunction.prototype.name. See also: thekeep_fnamescompress option. -
module(defaultfalse) -- Passtruean ES6 modules, where the toplevel scope is not the global scope. Impliestopleveland assumes input code is strict mode JS. -
nth_identifier(default: an internal mangler that weights based on character frequency analysis) -- Pass an object with aget(n)function that converts an ordinal into the nth most favored (usually shortest) identifier. Optionally also providereset(),sort(), andconsider(chars, delta)to use character frequency analysis of the source code. -
reserved(default[]) -- Pass an array of identifiers that should be excluded from mangling. Example:["foo", "bar"]. -
toplevel(defaultfalse) -- Passtrueto mangle names declared in the top level scope. -
safari10(defaultfalse) -- Passtrueto work around the Safari 10 loop iterator bug "Cannot declare a let variable twice". See also: thesafari10format option.
Examples:
// test.js
var globalVar;
function funcName(firstLongName, anotherLongName) {
var myVariable = firstLongName + anotherLongName;
}
var code = fs.readFileSync("test.js", "utf8");
await minify(code).code;
// 'function funcName(a,n){}var globalVar;'
await minify(code, { mangle: { reserved: ['firstLongName'] } }).code;
// 'function funcName(firstLongName,a){}var globalVar;'
await minify(code, { mangle: { toplevel: true } }).code;
// 'function n(n,a){}var a;'
Mangle properties options
-
builtins(default:false) — Usetrueto allow the mangling of builtin DOM properties. Not recommended to override this setting. -
debug(default:false) — Mangle names with the original name still present. Pass an empty string""to enable, or a non-empty string to set the debug suffix. -
keep_quoted(default:false) — How quoting properties ({"prop": ...}andobj["prop"]) controls what gets mangled."strict"(recommended) --obj.propis mangled.false--obj["prop"]is mangled.true--obj.propis mangled unless there isobj["prop"]elsewhere in the code.
-
nth_identifier(default: an internal mangler that weights based on character frequency analysis) -- Pass an object with aget(n)function that converts an ordinal into the nth most favored (usually shortest) identifier. Optionally also providereset(),sort(), andconsider(chars, delta)to use character frequency analysis of the source code. -
regex(default:null) — Pass a RegExp literal or pattern string to only mangle property matching the regular expression. -
reserved(default:[]) — Do not mangle property names listed in thereservedarray. -
undeclared(default:false) - Mangle those names when they are accessed as properties of known top level variables but their declarations are never found in input code. May be useful when only minifying parts of a project. See #397 for more details.
Format options
These options control the format of Terser's output code. Previously known as "output options".
-
ascii_only(defaultfalse) -- escape Unicode characters in strings and regexps (affects directives with non-ascii characters becoming invalid) -
beautify(defaultfalse) -- (DEPRECATED) whether to beautify the output. When using the legacy-bCLI flag, this is set to true by default. -
braces(defaultfalse) -- always insert braces inif,for,do,whileorwithstatements, even if their body is a single statement. -
comments(default"some") -- by default it keeps JSDoc-style comments that contain "@license", "@copyright", "@preserve" or start with!, passtrueor"all"to preserve all comments,falseto omit comments in the output, a regular expression string (e.g./^!/) or a function. -
ecma(default5) -- set desired EcmaScript standard version for output. Setecmato2015or greater to emit shorthand object properties - i.e.:{a}instead of{a: a}. Theecmaoption will only change the output in direct control of the beautifier. Non-compatible features in your input will still be output as is. For example: anecmasetting of5will not convert modern code to ES5. -
indent_level(default4) -
indent_start(default0) -- prefix all lines by that many spaces -
inline_script(defaulttrue) -- escape HTML comments and the slash in occurrences of</script>in strings -
keep_numbers(defaultfalse) -- keep number literals as it was in original code (disables optimizations like converting1000000into1e6) -
keep_quoted_props(defaultfalse) -- when turned on, prevents stripping quotes from property names in object literals. -
max_line_len(defaultfalse) -- maximum line length (for minified code) -
preamble(defaultnull) -- when passed it must be a string and it will be prepended to the output literally. The source map will adjust for this text. Can be used to insert a comment containing licensing information, for example. -
quote_keys(defaultfalse) -- passtrueto quote all keys in literal objects -
quote_style(default0) -- preferred quote style for strings (affects quoted property names and directives as well):0-- prefers double quotes, switches to single quotes when there are more double quotes in the string itself.0is best for gzip size.1-- always use single quotes2-- always use double quotes3-- always use the original quotes
-
preserve_annotations-- (defaultfalse) -- Preserve Terser annotations in the output. -
safari10(defaultfalse) -- set this option totrueto work around the Safari 10/11 await bug. See also: thesafari10mangle option. -
semicolons(defaulttrue) -- separate statements with semicolons. If you passfalsethen whenever possible we will use a newline instead of a semicolon, leading to more readable output of minified code (size before gzip could be smaller; size after gzip insignificantly larger). -
shebang(defaulttrue) -- preserve shebang#!in preamble (bash scripts) -
spidermonkey(defaultfalse) -- produce a Spidermonkey (Mozilla) AST -
webkit(defaultfalse) -- enable workarounds for WebKit bugs. PhantomJS users should set this option totrue. -
wrap_iife(defaultfalse) -- passtrueto wrap immediately invoked function expressions. See #640 for more details. -
wrap_func_args(defaultfalse) -- passtruein order to wrap function expressions that are passed as arguments, in parenthesis. See OptimizeJS for more details.