Skip to content

参考

基于 Terser / esbuild / SWC / lightningcss / cssnano / html-minifier-terser 官方文档编写,对照 Vite 7 / Webpack 5 稳定版

速查

  • JS 三压缩器:Terser(标杆)/ esbuild(Go,最快通用)/ SWC(Rust,Next.js/Rspack)/ Oxc(Vite 7 默认,比 terser 快 30~90x)
  • mangle 默认:Terser mangle:true / esbuild minifyIdentifiers:true / SWC mangle:true
  • keep names:Terser keep_classnames:true+keep_fnames:true / esbuild keepNames:true / SWC mangle.keepClassNames:true+keepFnNames:true
  • CSS:lightningcss(Rust,Vite 7 默认,一体化)/ cssnano(PostCSS,preset 系统)
  • HTML:html-minifier-terser(默认全关需显式开启)
  • Vite 7build.minify='oxc'build.cssMinify='lightningcss'、SSR build.minify=false
  • Webpack 5optimization.minimize=true(仅 production),内置 TerserPlugin,CSS 必须手动加
  • legalComments:esbuild 五种(none/inline/eof/linked/external)
  • 生产开 / 开发关:mangle 干扰调试
  • 边界:HTTP gzip/brotli 归【网络优化】叶
  • 完整说明见 入门 / 核心原理与配置

JS 压缩器对比表

维度TerseresbuildSWCOxc
语言JSGoRustRust
默认集成Webpack 5Vite 6 及之前Next.js / RspackVite 7+
压缩率标杆(最高)略低 0.5~2%接近 Terser接近 esbuild
速度慢(分钟级)极快(秒级)快(秒级)极快(30~90x terser)
compress 选项完整子集几乎一一对应 TerserTerser 子集
manglemangle:trueminifyIdentifiers:truemangle:true内置
keep nameskeep_classnames+keep_fnameskeepNamesmangle.keepClassNames+keepFnNames内置
drop_consolecompress.drop_consoledrop:['console']compress.drop_console支持
pure_funcscompress.pure_funcspure:['fn']compress.pure_funcs支持
passescompress.passes单次compress.passes(0=无限)单次
APIminify(code, opts)esbuild.transform/buildswc.minify/minifySync内置
legalCommentsformat.commentslegalCommentsformat.comments支持

Terser 完整选项清单

compress 子选项

选项默认作用
arrowstrue转换 function() {}() => {}(需 ecma≥2015)
booleanstrue优化布尔(true!0
collapse_varstrue内联单次使用变量
comparisonstrue优化比较(a === b vs a == b
computed_propstrueobj['foo']obj.foo
conditionalstrue优化条件表达式
dead_codetrue删不可达
drop_consolefalse(可传数组)console.*
drop_debuggertruedebugger
ecma52015+ 启用 ES6+ 形态
evaluatetrue常量折叠
hoist_funsfalse函数声明上提
hoist_propstrue把常量对象属性提到顶层
hoist_varsfalse变量声明上提
if_returntrueif (a) return b; return c;return a?b:c;
inline1函数内联(0/1/2/3)
join_varstrue合并 var 声明
keep_classnamesfalse(可正则)保留类名
keep_fargstrue保留未用函数参数
keep_fnamesfalse(可正则)保留函数名
keep_infinityfalse不把 Infinity1/0
loopstrue优化循环
negate_iifetrue否定 IIFE 让 compress 更激进
passes1多次扫描(建议 2~3)
propertiestrueobj['foo']obj.foo
pure_funcs[]标记无副作用函数
pure_gettersfalse(可传 'strict'假设属性访问无副作用
reduce_funcstrue内联单次用函数
reduce_varstrue优化单次用变量
sequencestrue(可传数字限制), 合并语句
side_effectstrue删无副作用表达式
switchestrue优化 switch
toplevelfalse顶层变量也压缩
top_retainnull排除特定顶层
typeofstrue优化 typeof
unsafefalse启用所有 unsafe_*
unsafe_arrowsfalse函数转箭头
unsafe_compsfalse改比较语义
unsafe_Functionfalse优化 new Function
unsafe_mathfalse优化数学(可能改浮点)
unsafe_methodsfalseObject.assign{...a, ...b}
unsafe_protofalse重写原型访问
unsafe_regexpfalse把 RegExp 转字符串
unsafe_symbolsfalseSymbol 转字符串
unsafe_undefinedfalse用 void 0 替 undefined
unusedtrue删未引用

mangle 子选项

选项默认作用
evalfalse在 eval 作用域也 mangle
keep_classnamesfalse(可正则)保留类名
keep_fnamesfalse(可正则)保留函数名
modulefalseES module 模式
nth_identifier内置提供标识符生成器
reserved[]排除特定标识符
safari10falseSafari 10/11 兼容
toplevelfalse顶层也 mangle
propertiesfalsemangle 属性名(慎用)

format 子选项

选项默认作用
beautifyfalse美化输出
comments'some'保留 @license/@preserve/! 注释
ecma5输出目标版本
indent_level4美化缩进
preamble''前置文本
preserve_annotationsfalse保留 /*#__PURE__*/
quote_keysfalse总是引号包裹 key
quote_style0引号风格(0最优/1单/2双/3强制)
semicolonstrue; 分隔(false 用 \n
wrap_func_argstrue包裹函数参数
wrap_iifefalse包裹 IIFE

esbuild 完整选项

三合一 minify

bash
--minify                  # 全开
--minify-whitespace       # 只去空白
--minify-identifiers      # 只重命名
--minify-syntax           # 只重写语法

关键选项

选项作用
--target=浏览器目标,决定语法降级(如 es6chrome111,firefox114,safari16
--keep-names保留函数/类的 .name
--drop=删指定标识符(如 consoledebugger
--pure=标记无副作用函数
--mangle-props=mangle 匹配的属性(正则)
--legal-comments=none/inline/eof/linked/external
--format=iife/cjs/esm
--banner=文件头插入
--footer=文件尾插入
--sourcemap=true/false/'external'

默认 legalComments 行为

  • 非 bundling(transform):默认 inline
  • bundling(build):默认 eof

SWC 完整选项(jsc.minify)

json
{
  "minify": true,
  "jsc": {
    "minify": {
      "compress": {
        "arguments": false,
        "arrows": true,
        "booleans": true,
        "booleans_as_integers": false,
        "collapse_vars": true,
        "comparisons": true,
        "computed_props": true,
        "conditionals": true,
        "dead_code": true,
        "defaults": true,
        "directives": true,
        "drop_console": false,
        "drop_debugger": true,
        "ecma": 5,
        "evaluate": true,
        "expression": true,
        "hoist_funs": false,
        "hoist_props": true,
        "hoist_vars": false,
        "if_return": true,
        "inline": 1,
        "join_vars": true,
        "keep_classnames": false,
        "keep_fargs": false,
        "keep_fnames": false,
        "keep_infinity": false,
        "loops": true,
        "negate_iife": true,
        "passes": 0,
        "properties": true,
        "pure_funcs": [],
        "pure_getters": false,
        "reduce_funcs": false,
        "reduce_vars": true,
        "sequences": 0,
        "side_effects": true,
        "switches": true,
        "toplevel": true,
        "top_retain": [],
        "typeofs": true,
        "unsafe": false,
        "unsafe_arrows": false,
        "unsafe_comps": false,
        "unsafe_Function": false,
        "unsafe_math": false,
        "unsafe_methods": false,
        "unsafe_proto": false,
        "unsafe_regexp": false,
        "unsafe_symbols": false,
        "unsafe_undefined": false,
        "unused": true
      },
      "mangle": {
        "topLevel": true,
        "keepClassNames": false,
        "keepFnNames": false,
        "keepPrivateProps": false,
        "ie8": false,
        "safari10": false,
        "reserved": []
      },
      "format": {
        "comments": "some",
        "asciiOnly": false,
        "beautify": false,
        "ecma": 5,
        "indentLevel": 4,
        "preamble": "",
        "preserveAnnotations": false,
        "quoteKeys": false,
        "quoteStyle": 0,
        "semicolons": true,
        "shebang": true,
        "wrapFuncArgs": true,
        "wrapIIFE": false,
        "inlineScript": false
      }
    }
  }
}

SWC 与 Terser 关键差异

选项TerserSWC
keep_fargs 默认truefalse
toplevel 默认falsetrue
reduce_funcs 默认truefalse
passes 默认10(无限,需配合谨慎用)
命名风格snake_casecamelCase
format 大部分选项全实现多为 noop(为兼容 terser 配置)

lightningcss 配置速查

编程式 API

js
import { transform, browserslistToTargets, composeVisitors } from 'lightningcss';
import browserslist from 'browserslist';

const { code, map } = transform({
  filename: 'input.css',
  code: Buffer.from(cssCode),
  minify: true,
  sourceMap: true,
  targets: browserslistToTargets(browserslist('>= 0.25%')),
  errorRecovery: true,
  nonStandard: { deepSelectorCombinator: true },
  visitor: { ... },  // 自定义 visitor
  drafts: { customMedia: true, nesting: true },
  unusedSymbols: ['unused-class'],  // 标记 DCE
});

CLI

bash
lightningcss \
  --minify \
  --bundle \
  --targets ">= 0.25%" \
  --sourcemap \
  input.css \
  -o output.css

targets 写法

js
// 用 browserslist 字符串
targets: browserslistToTargets(browserslist('>= 0.25%'))

// 显式版本
targets: {
  chrome: 111 << 16,   // 111.0.0
  edge: 111 << 16,
  firefox: 114 << 16,
  safari: 16 << 16 | 4 << 8,  // 16.4
  ios: 16 << 16 | 4 << 8,
}

cssnano 配置速查

Preset 选择

preset风格用法
default安全(默认)preset: 'default'
advanced激进preset: 'advanced'
lite仅基础preset: 'lite'

配置位置(按优先级)

  1. package.jsoncssnano 字段
  2. cssnano.config.js
  3. postcss.config.js 中的 cssnano plugin

选项清单

选项(去 postcss- 前缀)作用
discardComments删注释
discardDuplicates删重复规则
discardEmpty删空规则
discardOverridden删被覆盖的规则
discardUnused删未使用的规则(需传入 whitelist)
mergeRules合并相同选择器
mergeMediaQueries合并 media query
minifyFontValues缩写字体值
minifyGradients缩写渐变
minifyParams缩写参数
minifySelectors缩写选择器
normalizeCharset规范 charset
normalizeDisplayValues规范 display
normalizePositions规范 position
normalizeRepeatStyle规范 repeat
normalizeString规范字符串
normalizeTimingFunctions规范 timing
normalizeUnicode规范 unicode-range
normalizeUrl规范 url
normalizeWhitespace规范空白
orderedValues排序属性值
reduceCalc简化 calc(advanced)
reduceInitial用 initial 替代
reduceTransforms简化 transform
svgo用 SVGO 压 SVG
uniqueSelectors去重选择器

html-minifier-terser 配置速查

完整选项

选项默认作用
caseSensitivefalse大小写敏感(XML 模式)
collapseWhitespacefalse折叠空白(必开)
conservativeCollapsefalse配合 collapseWhitespace,保留单空格
collapseInlineTagWhitespacefalseinline 标签间也去空白
decodeEntitiesfalse转义字符解码
html5trueHTML5 解析
ignoreCustomComments[]保留指定注释(正则)
ignoreCustomFragments[]保留指定片段(如 PHP)
keepClosingSlashfalse保留自闭合标签的斜杠(XHTML)
maxLineLengthfalse强制换行(gzip 友好)
minifyCSSfalse用 clean-css 压内联 CSS
minifyJSfalse用 Terser 压内联 JS
minifyURLsfalse用 relateurl 缩 URL
preserveLineBreaksfalse保留换行
preventAttributesEscapingfalse阻止属性转义
processConditionalCommentsfalse处理 IE 条件注释
processScripts[]压指定 type 的 script 内容(如 text/ng-template
quoteCharacter"引号字符
removeCommentsfalse删注释
removeEmptyAttributesfalse删空属性
removeEmptyElementsfalse删空元素(慎用)
removeOptionalTagsfalse删可省标签
removeRedundantAttributesfalse删冗余属性
removeScriptTypeAttributesfalse删 script 的 type
removeStyleLinkTypeAttributesfalse删 style/link 的 type
sortAttributesfalse排序属性(gzip 友好)
sortClassNamefalse排序 class
trimCustomFragmentsfalse修剪自定义片段
useShortDoctypefalse短 doctype

推荐生产档

js
{
  collapseWhitespace: true,
  conservativeCollapse: true,
  removeComments: true,
  removeEmptyAttributes: true,
  removeRedundantAttributes: true,
  removeOptionalTags: false,  // 谨慎,可能破坏 Vue/React 注释节点
  removeScriptTypeAttributes: true,
  removeStyleLinkTypeAttributes: true,
  useShortDoctype: true,
  sortAttributes: true,
  sortClassName: true,
  minifyCSS: true,
  minifyJS: true,
  html5: true,
  decodeEntities: true,
}

Vite build 选项清单

选项默认说明
build.minify'oxc'(client)/ false(SSR)'oxc'/'terser'/'esbuild'(deprecated)/false
build.cssMinify'lightningcss''lightningcss'/'esbuild'/false
build.terserOptions{}仅当 minify='terser' 生效;额外支持 maxWorkers
build.target'baseline-widely-available'string / string[]
build.cssTargetbuild.target可独立
build.sourcemapfalsetrue/'inline'/'hidden'
build.chunkSizeWarningLimit500(KB,未压缩)警告阈值
build.reportCompressedSizetrue报 gzip 大小(大项目可关)
build.cssCodeSplittrueCSS 代码分割
build.assetsInlineLimit4096(B)内联为 base64 阈值
build.libundefined库模式
build.rollupOptions{}透传 Rollup 选项

Webpack optimization 选项清单

选项默认说明
optimization.minimizemode==='production'总开关
optimization.minimizer[TerserPlugin]数组,写入任何会覆盖默认
optimization.usedExportstrue(prod)tree shaking 标记
optimization.sideEffectstrue(prod)读 package.json sideEffects
optimization.splitChunks{ chunks: 'async' }(prod)代码分割
optimization.runtimeChunkfalseruntime 分包
optimization.moduleIds'deterministic'模块 ID 算法
optimization.chunkIds'deterministic'chunk ID 算法
optimization.nodeEnvmodeprocess.env.NODE_ENV
optimization.mangleWasmImportsfalseWASM import 混淆
optimization.removeAvailableModulestrue(prod)删已可用模块
optimization.removeEmptyChunkstrue删空 chunk

terser-webpack-plugin 选项

选项默认说明
test所有 .js/.cjs/.mjs匹配文件
include全部包含文件
exclude排除文件
paralleltrue多进程
minifyTerserPlugin.terserMinify可换 SWC/esbuild:TerserPlugin.swcMinify/TerserPlugin.esbuildMinify
terserOptions见上透传 Terser
extractCommentstrue(提取到 LICENSE.txt)license 注释抽离

用 SWC 替换 Terser

js
const TerserPlugin = require('terser-webpack-plugin');

new TerserPlugin({
  minify: TerserPlugin.swcMinify,
  terserOptions: {
    compress: { drop_console: true },
    mangle: true,
  },
})

版本与运行环境

工具当前稳定版状态
Terser5.x维护中,仍是 Webpack 5 默认、压缩率标杆
esbuild0.25+稳定迭代,社区主流
swc1.x持续维护,Next.js/Rspack 默认
Oxc1.x+Vite 7 默认,Rust 工具链
lightningcss1.x逐步取代 cssnano 成主流
cssnano7.x仍维护,基于 PostCSS
html-minifier-terser7.2.0html-minifier 的 Terser 维护分支
Vite7+minify:'oxc'cssMinify:'lightningcss'
Webpack5.xterser-webpack-plugin 默认
Next.js15+SWC 默认
Rspack1.xSWC 默认

重大版本变化

  • Vite 7(2026):build.minify 默认从 'esbuild''oxc''esbuild' 选项 deprecated;build.cssMinify 默认从 'esbuild''lightningcss'build.target 默认变 'baseline-widely-available'
  • Vite 5+build.target 默认 'modules'(原生 ES module)
  • Webpack 5:内置 terser-webpack-plugin,移除 webpack 4 的 UglifyJS
  • Next.js 12:从 Babel 切换到 SWC

官方资源