Skip to main content

API 参考

假设通过 NPM 安装,你可以像这样在应用中加载 Terser:

¥Assuming installation via NPM, you can load Terser in your application like this:

const { minify } = require("terser");

或者,

¥Or,

import { minify } from "terser";

还支持浏览器加载。它公开了一个包含 .minify 属性的全局变量 Terser

¥Browser loading is also supported. It exposes a global variable Terser containing a .minify property:

<script src="https://cdn.jsdelivr.net/npm/source-map@0.7.3/dist/source-map.js"></script>
<script src="https://cdn.jsdelivr.net/npm/terser/dist/bundle.min.js"></script>

有一个异步高级函数 async minify(code, options),它将以可配置的方式执行所有压缩 阶段。默认情况下,minify() 将启用 compressmangle。示例:

¥There is an async high level function, async minify(code, options), which will perform all minification phases in a configurable manner. By default minify() will enable compress and mangle. Example:

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_sync() 替代版本,立即返回。

¥There is also a minify_sync() alternative version of it, which returns instantly.

你可以通过使用第一个参数的对象一次 minify 多个 JavaScript 文件,其中键是文件名,值是源代码:

¥You can minify more than one JavaScript file at a time by using an object for the first argument where the keys are file names and the values are source code:

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));

toplevel 选项:

¥The toplevel option:

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);

nameCache 选项:

¥The nameCache option:

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));

你可以通过以下方式将名称缓存持久保存到文件系统:

¥You may persist the name cache to the file system in the following way:

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");

minify() 选项组合的示例:

¥An example of a combination of minify() options:

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);"

错误示例:

¥An error example:

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
}

压缩选项

¥Minify options

  • ecma (默认值 undefined) -

通过 520152016 等来覆盖 compressformatecma 选项。

¥pass 5, 2015, 2016, etc to override compress and format's ecma options.

  • enclose (默认值 false) -

传递 true"args[:values]" 格式的字符串,其中 argsvalues 分别是逗号分隔的参数名称和值,以将输出嵌入到具有可配置参数和值的大函数中。

¥pass true, or a string in the format of "args[:values]", where args and values are comma-separated argument names and values, respectively, to embed the output in a big function with the configurable arguments and values.

  • parse(默认 {})— 如果你希望指定一些额外的 解析选项,则传递一个对象。

    ¥parse (default {}) — pass an object if you wish to specify some additional parse options.

  • compress(默认 {})— 传递 false 以完全跳过压缩。传递一个对象来指定自定义 压缩选项

    ¥compress (default {}) — pass false to skip compressing entirely. Pass an object to specify custom compress options.

  • mangle(默认 true)— 传递 false 以跳过名称修改,或传递对象以指定 混淆选项(见下文)。

    ¥mangle (default true) — pass false to skip mangling names, or pass an object to specify mangle options (see below).

    • mangle.properties(默认 false)— mangle 选项的子类别。传递一个对象来指定自定义 破坏属性选项

      ¥mangle.properties (default false) — a subcategory of the mangle option. Pass an object to specify custom mangle property options.

  • module(默认 false)— 压缩 ES6 模块时使用。"使用严格" 是隐含的,并且名称可以在顶部范围内被破坏。如果启用 compressmangle,则将启用 toplevel 选项。

    ¥module (default false) — Use when minifying an ES6 module. "use strict" is implied and names can be mangled on the top scope. If compress or mangle is enabled then the toplevel option will be enabled.

  • formatoutput(默认 null)— 如果你希望指定额外的 格式选项,则传递一个对象。默认值已针对最佳压缩进行了优化。

    ¥format or output (default null) — pass an object if you wish to specify additional format options. The defaults are optimized for best compression.

  • sourceMap (默认值 false) -

如果你想指定 源映射选项,请传递一个对象。

¥pass an object if you wish to specify source map options.

  • toplevel (默认值 false) -

如果你希望启用顶层变量和函数名称修改并删除未使用的变量和函数,请设置为 true

¥set to true if you wish to enable top level variable and function name mangling and to drop unused variables and functions.

  • nameCache (默认值 null) -

如果你希望在多次调用 minify() 时缓存混淆的变量和属性名称,请传递空对象 {} 或以前使用过的 nameCache 对象。注意:这是一个读/写属性。minify() 将读取该对象的名称缓存状态并在压缩期间更新它,以便用户可以重用或在外部保留它。

¥pass an empty object {} or a previously used nameCache object if you wish to cache mangled variable and property names across multiple invocations of minify(). Note: this is a read/write property. minify() will read the name cache state of this object and update it during minification so that it may be reused or externally persisted by the user.

  • ie8 (默认值 false) -

设置为 true 以支持 IE8。

¥set to true to support IE8.

  • keep_classnames (默认值: undefined) -

通过 true 以防止丢弃或混淆类名。传递正则表达式以仅保留与该正则表达式匹配的类名。

¥pass true to prevent discarding or mangling of class names. Pass a regular expression to only keep class names matching that regex.

  • keep_fnames (默认值: false) -

传递 true 以防止丢弃或修改函数名称。传递正则表达式以仅保留与该正则表达式匹配的函数名称。对于依赖 Function.prototype.name 的代码很有用。如果顶层压缩选项 keep_classnamesundefined,它将被顶层压缩选项 keep_fnames 的值覆盖。

¥pass true to prevent discarding or mangling of function names. Pass a regular expression to only keep function names matching that regex. Useful for code relying on Function.prototype.name. If the top level minify option keep_classnames is undefined it will be overridden with the value of the top level minify option keep_fnames.

  • safari10 (默认值: false) -

传递 true 来解决 Safari 10/11 循环范围和 await 中的错误。详细信息请参见 mangleformat 中的 safari10 选项。

¥pass true to work around Safari 10/11 bugs in loop scoping and await. See safari10 options in mangle and format for details.

压缩选项结构

¥Minify options structure

{
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
}

源映射选项

¥Source map options

要生成源映射:

¥To generate a source map:

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

请注意,源映射并未保存在文件中,它只是在 result.map 中返回。为 sourceMap.url 传递的值仅用于设置 result.code 中的 //# sourceMappingURL=out.js.mapfilename 的值仅用于设置源映射文件中的 file 属性(请参阅 [the spec][sm-spec])。

¥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][sm-spec]) in source map file.

你可以将选项 sourceMap.url 设置为 "inline",源映射将附加到代码中。

¥You can set option sourceMap.url to be "inline" and source map will be appended to code.

你还可以指定要包含在源映射中的 sourceRoot 属性:

¥You can also specify sourceRoot property to be included in source map:

var result = await minify({"file1.js": "var a = function() {};"}, {
sourceMap: {
root: "http://example.com/src",
url: "out.js.map"
}
});

如果你正在压缩已编译的 JavaScript 并拥有其源映射,则可以使用 sourceMap.content

¥If you're compressing compiled JavaScript and have a source map for it, you can use sourceMap.content:

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`

如果你使用 X-SourceMap 标头,则可以省略 sourceMap.url

¥If you're using the X-SourceMap header instead, you can just omit sourceMap.url.

如果你碰巧需要源映射作为原始对象,请将 sourceMap.asObject 设置为 true

¥If you happen to need the source map as a raw object, set sourceMap.asObject to true.