压缩
¥Minification
本节适用于那些想要使用 SWC 作为构建过程最后一步的人。如果你想将 swc 压缩器与打包器一起使用,请参阅文档
¥This section is for people who want to use swc as a last step of the build process. If you want to use the swc minifier with a bundler, see the documentation for
- swcMinify with the Terser Webpack Plugin
-
如果你只想要最小化,SWC Minify Webpack Plugin 是一个独立的工具。
¥SWC Minify Webpack Plugin which is a standalone tool if you only want minification.
假设
¥Assumptions
SWC 压缩器做了一些假设,以提高压缩效率。这与其他压缩器类似。
¥SWC Minifier makes small amount of assumptions to make the minification efficient. This is similar to other minifiers.
-
.toString()和.valueOf()没有副作用,并且对于内置对象,它们未被覆盖。¥
.toString()and.valueOf()don’t have side effects, and for built-in objects they have not been overridden. -
undefined、NaN和Infinity未被外部重新定义。¥
undefined,NaNandInfinityhave not been externally redefined. -
arguments.callee、arguments.caller和Function.prototype.caller未被使用。¥
arguments.callee,arguments.callerandFunction.prototype.callerare not used.
在严格模式下,这些无效。
¥These are not valid in strict mode.
-
代码并不期望
Function.prototype.toString()或Error.prototype.stack的内容有任何特定含义。¥The code doesn’t expect the contents of
Function.prototype.toString()orError.prototype.stackto be anything in particular. -
获取和设置普通对象的属性不会引起其他副作用(使用
.watch()或Proxy)。¥Getting and setting properties on a plain object does not cause other side effects (using
.watch()orProxy). -
对象属性可以添加、删除和修改(
Object.defineProperty()、Object.defineProperties()、Object.freeze()、Object.preventExtensions()或Object.seal()不会阻止这些操作)。¥Object properties can be added, removed and modified (not prevented with
Object.defineProperty(),Object.defineProperties(),Object.freeze(),Object.preventExtensions()orObject.seal()). -
document.all不是null。¥
document.allis notnull. -
将属性赋值给类不会产生副作用,也不会抛出异常。
¥Assigning properties to a class doesn’t have side effects and does not throw.
-
访问已声明的顶层标识符不会产生副作用。
¥Acesssing declared top-level identifiers do not have side effects.
如果你在 globalThis 上使用具有副作用的 getter 声明变量,SWC Minifier 可能会破坏它。
¥If you declare a variable on globalThis using a getter with side-effects, SWC Minifier will likely break it.
-
不存在 TDZ 违规。
¥TDZ violation does not exist.
TDZ 违规将被忽略且不会保留。
¥TDZ violation will be ignored and not preserved.
-
算术表达式可能不会产生副作用。
¥Arithmetic expression may not have side effects.
此假设意味着你不能依赖 JS 引擎在将 bigint 和 number 相加时抛出的异常。
¥This assumption means that you can’t rely on the exception thrown by the JS engine when adding a bigint and a number.
const a = 1n;
const b = 1;
const c = a + b;如果你执行此代码,JS 引擎将抛出异常。但 SWC Minifier 会忽略它。
¥If you execute this code, the JS engine will throw an exception. But SWC Minifier will ignore it.
¥Related: terser - compiler assumptions
从 v1.2.67 开始,你可以通过在 .swcrc 文件中启用 minify 来配置 SWC 以缩小代码:
¥Starting with v1.2.67, you can configure SWC to minify your code by enabling minify in your .swcrc file:
{
// Enable minification
"minify": true,
// Optional, configure minification options
"jsc": {
"minify": {
"compress": {
"unused": true
},
"mangle": true
}
}
}配置
¥Configuration
关于注释的注意事项
¥Note about comments
如果你将 jsc.minify.compress 设置为 true 或 {},SWC 将删除从 v1.11.11 开始的所有注释。以前的版本将仅保留许可证注释。如果你不希望这样,请修改 jsc.minify.format。
¥If you set jsc.minify.compress to true or {}, SWC will remove all comments starting from v1.11.11.
Previous versions will preserve only license comments.
If you don’t want this, modify jsc.minify.format.
jsc.minify.compress
类型:boolean | object。
¥Type: boolean | object.
与 terser 的 压缩选项 类似。
¥Similar to the compress option of terser.
{
"jsc": {
"minify": {
"compress": true // equivalent to {}
}
}
}-
arguments,默认为false。¥
arguments, defaults tofalse. -
arrows,默认为true。¥
arrows, defaults totrue. -
booleans,默认为true。¥
booleans, defaults totrue. -
booleans_as_integers,默认为false。¥
booleans_as_integers, defaults tofalse. -
collapse_vars,默认为true。¥
collapse_vars, defaults totrue. -
comparisons,默认为true。¥
comparisons, defaults totrue. -
computed_props,默认为true。¥
computed_props, defaults totrue. -
conditionals,默认为true。¥
conditionals, defaults totrue. -
dead_code,默认为true。¥
dead_code, defaults totrue. -
defaults,默认为true。¥
defaults, defaults totrue. -
directives,默认为true。¥
directives, defaults totrue. -
drop_console,默认为false。¥
drop_console, defaults tofalse. -
drop_debugger,默认为true。¥
drop_debugger, defaults totrue. -
ecma,默认为5。¥
ecma, defaults to5. -
evaluate,默认为true。¥
evaluate, defaults totrue. -
global_defs,默认为{}。¥
global_defs, defaults to{}. -
hoist_funs,默认为false。¥
hoist_funs, defaults tofalse. -
hoist_props,默认为true。¥
hoist_props, defaults totrue. -
hoist_vars,默认为false。¥
hoist_vars, defaults tofalse. -
ie8,忽略。¥
ie8, Ignored. -
if_return,默认为true。¥
if_return, defaults totrue. -
inline,默认为true。¥
inline, defaults totrue. -
join_vars,默认为true。¥
join_vars, defaults totrue. -
keep_classnames,默认为false。¥
keep_classnames, defaults tofalse. -
keep_fargs,默认为false。¥
keep_fargs, defaults tofalse. -
keep_infinity,默认为false。¥
keep_infinity, defaults tofalse. -
loops,默认为true。¥
loops, defaults totrue. -
negate_iife,默认为true。¥
negate_iife, defaults totrue. -
passes,默认为0,表示不限制。¥
passes, defaults to0, which means no limit. -
properties,默认为true。¥
properties, defaults totrue. -
pure_getters,默认为 “.¥
pure_getters, defaults to “. -
pure_funcs,默认为[]。类型是字符串数组。¥
pure_funcs, defaults to[]. Type is an array of string. -
reduce_funcs,默认为false。¥
reduce_funcs, defaults tofalse. -
reduce_vars,默认为true。¥
reduce_vars, defaults totrue. -
sequences,默认为true。¥
sequences, defaults totrue. -
side_effects,默认为true。¥
side_effects, defaults totrue. -
switches,默认为true。¥
switches, defaults totrue. -
top_retain,默认为 “.¥
top_retain, defaults to “. -
toplevel,默认为true。¥
toplevel, defaults totrue. -
typeofs,默认为true。¥
typeofs, defaults totrue. -
unsafe,默认为false。¥
unsafe, defaults tofalse. -
unsafe_arrows,默认为false。¥
unsafe_arrows, defaults tofalse. -
unsafe_comps,默认为false。¥
unsafe_comps, defaults tofalse. -
unsafe_Function,默认为false。¥
unsafe_Function, defaults tofalse. -
unsafe_math,默认为false。¥
unsafe_math, defaults tofalse. -
unsafe_symbols,默认为false。¥
unsafe_symbols, defaults tofalse. -
unsafe_methods,默认为false。¥
unsafe_methods, defaults tofalse. -
unsafe_proto,默认为false。¥
unsafe_proto, defaults tofalse. -
unsafe_regexp,默认为false。¥
unsafe_regexp, defaults tofalse. -
unsafe_undefined,默认为false。¥
unsafe_undefined, defaults tofalse. -
unused,默认为true。¥
unused, defaults totrue. -
module,忽略。目前,所有文件都被视为模块。¥
module, Ignored. Currently, all files are treated as module.
jsc.minify.mangle
类型:boolean | object。
¥Type: boolean | object.
与 terser 的 损坏选项 类似。
¥Similar to the mangle option of terser.
{
"jsc": {
"minify": {
"mangle": true // equivalent to {}
}
}
}-
props,默认为false,true与{}相同。¥
props, Defaults tofalse, andtrueis identical to{}. -
topLevel,默认为true。别名为toplevel以与terser兼容。¥
topLevel, Defaults totrue. Aliased astoplevelfor compatibility withterser. -
keepClassNames,默认为false。别名为keep_classnames以与terser兼容。¥
keepClassNames, Defaults tofalse. Aliased askeep_classnamesfor compatibility withterser. -
keepFnNames,默认为false。¥
keepFnNames, Defaults tofalse. -
keepPrivateProps,默认为false。别名为keep_private_props以与terser兼容。¥
keepPrivateProps, Defaults tofalse. Aliased askeep_private_propsfor compatibility withterser. -
reserved,默认为[]¥
reserved, Defaults to[] -
ie8,忽略。¥
ie8, Ignored. -
safari10,默认为false。¥
safari10, Defaults tofalse.
jsc.minify.mangle.properties
类型:object。
¥Type: object.
与 terser 的 mangle 属性选项 类似。
¥Similar to the mangle properties option of terser.
{
"jsc": {
"minify": {
"mangle":{
"properties":{
"reserved": ["foo", "bar"],
"undeclared":false,
"regex":"rust regex"
}
}
}
}
}-
reserved:不要将这些名称用作属性。¥
reserved: Don’t use these names as properties. -
undeclared:即使未声明,也会损坏属性。¥
undeclared: Mangle properties even if it’s not declared. -
regex:仅当与此正则表达式匹配时才处理属性¥
regex: Mangle properties only if it matches this regex
jsc.minify.format
这些属性大多尚未实现,但它的存在是为了支持将 terser 配置传递到 swc minify 而不进行修改。
¥These properties are mostly not implemented yet, but it exists to support passing terser config to swc minify without modification.
-
asciiOnly,默认为false。实现为v1.2.184并别名为ascii_only以与terser兼容。¥
asciiOnly, Defaults tofalse. Implemented asv1.2.184and aliased asascii_onlyfor compatibility withterser. -
beautify,默认为false。目前没有。¥
beautify, Defaults tofalse. Currently noop. -
braces,默认为false。目前没有。¥
braces, Defaults tofalse. Currently noop. -
comments,默认为some。¥
comments, Defaults tosome.-
false删除所有注释¥
falseremoves all comments -
'some'保留一些注释¥
'some'preserves some comments -
'all'保留所有注释¥
'all'preserves all comments
-
-
ecma,默认为 5。目前没有。¥
ecma, Defaults to 5. Currently noop. -
indentLevel,目前 noop 和别名为indent_level以兼容terser。¥
indentLevel, Currently noop and aliases asindent_levelfor compatibility withterser. -
indentStart,目前 noop 和别名为indent_start以兼容terser。¥
indentStart, Currently noop and aliases asindent_startfor compatibility withterser. -
inlineScript,别名为inline_script以兼容terser,需要@swc/core@1.9.2或更高版本。¥
inlineScript, Aliases asinline_scriptfor compatibility withterserand requires@swc/core@1.9.2or later. -
keepNumbers,目前 noop 和别名为keep_numbers以兼容terser。¥
keepNumbers, Currently noop and aliases askeep_numbersfor compatibility withterser. -
keepQuotedProps,目前 noop 和别名为keep_quoted_props以兼容terser。¥
keepQuotedProps, Currently noop and aliases askeep_quoted_propsfor compatibility withterser. -
maxLineLen,当前为 noop,别名为max_line_len以兼容terser。¥
maxLineLen, Currently noop, and aliases asmax_line_lenfor compatibility withterser. -
preamble,从v1.3.66开始支持。¥
preamble, Supported sincev1.3.66. -
quoteKeys,目前 noop 和别名为quote_keys以兼容terser。¥
quoteKeys, Currently noop and aliases asquote_keysfor compatibility withterser. -
quoteStyle,目前 noop 和别名为quote_style以兼容terser。¥
quoteStyle, Currently noop and aliases asquote_stylefor compatibility withterser. -
preserveAnnotations,目前 noop 和别名为preserve_annotations以兼容terser。¥
preserveAnnotations, Currently noop and aliases aspreserve_annotationsfor compatibility withterser. -
safari10,目前无操作。¥
safari10, Currently noop. -
semicolons,目前无操作。¥
semicolons, Currently noop. -
shebang,目前无操作。¥
shebang, Currently noop. -
webkit,目前无操作。¥
webkit, Currently noop. -
wrapIife,目前 noop 和别名为wrap_iife以兼容terser。¥
wrapIife, Currently noop and aliases aswrap_iifefor compatibility withterser. -
wrapFuncArgs,目前 noop 和别名为wrap_func_args以兼容terser。¥
wrapFuncArgs, Currently noop and aliases aswrap_func_argsfor compatibility withterser.
@swc/core Usage
swc.minify(code, options)
该 API 是异步的,所有解析、缩小和代码生成都将在后台线程中完成。options 参数与 jsc.minify 对象相同。例如:
¥This API is asynchronous and all of parsing, minification, and code generation will be done in background thread. The options argument is same as jsc.minify object. For example:
import swc from "@swc/core";
const { code, map } = await swc.minify(
"import foo from '@src/app'; console.log(foo)",
{
compress: false,
mangle: true,
}
);
expect(code).toMatchInlineSnapshot(`"import a from'@src/app';console.log(a);"`);返回 Promise<{ code: string, map: string }>。
¥Returns Promise<{ code: string, map: string }>.
swc.minifySync(code, options)
该 API 存在于 @swc/core、@swc/wasm、@swc/wasm-web 上。
¥This API exists on @swc/core, @swc/wasm, @swc/wasm-web.
import swc from "@swc/core";
const { code, map } = swc.minifySync(
"import foo from '@src/app'; console.log(foo)",
{
compress: false,
mangle: true,
module: true
}
);
expect(code).toMatchInlineSnapshot(`"import a from'@src/app';console.log(a);"`);返回 { code: string, map: string }。
¥Returns { code: string, map: string }.
WebAssembly 的 API
¥APIs for WebAssembly
替换 Terser
¥Replacing Terser
你可以减少构建时间并覆盖 Terser,而无需库通过 Yarn 解析 更新其依赖。示例 package.json 将包括:
¥You can reduce build time and override Terser without needing a library to update their dependencies through yarn resolutions . Example package.json would include:
{
"resolutions": { "terser": "npm:@swc/core" }
}对于所有嵌套依赖,这将使用 SWC 压缩器而不是 Terser。确保删除锁定文件并重新安装依赖。
¥This will use the SWC minifier instead of Terser for all nested dependencies. Ensure you remove your lockfile and re-install your dependencies.
$ rm -rf node_modules yarn.lock
$ yarn