跳到主要内容

babel-preset-minify

安装

npm install babel-preset-minify --save-dev

用法

通过配置文件(推荐)

babel.config.json
{
"presets": ["minify"]
}

或通过参数设置 -

babel.config.json
{
"presets": [["minify", {
"mangle": {
"exclude": ["MyCustomError"]
},
"unsafe": {
"typeConstructors": false
},
"keepFnName": true
}]]
}

通过命令行工具(CLI)

Shell
babel script.js --presets minify

通过 Node API

JavaScript
require("@babel/core").transformSync("code", {
presets: ["minify"]
});

参数

有两种类型的参数:

  1. 通过插件一比一地映射
  2. 相同的参数传递给多个插件

通过插件一比一地映射

  • false - 关闭插件
  • true - 开启插件
  • { ...pluginOpts } - 开启插件并将 pluginOpts 传递给插件
参数名插件默认值
booleanstransform-minify-booleanstrue
builtInsminify-builtinstrue
consecutiveAddstransform-inline-consecutive-addstrue
deadcodeminify-dead-code-eliminationtrue
evaluateminify-constant-foldingtrue
flipComparisonsminify-flip-comparisonstrue
guardsminify-guarded-expressionstrue
infinityminify-infinitytrue
mangleminify-mangle-namestrue
memberExpressionstransform-member-expression-literalstrue
mergeVarstransform-merge-sibling-variablestrue
numericLiteralsminify-numeric-literalstrue
propertyLiteralstransform-property-literalstrue
regexpConstructorstransform-regexp-constructorstrue
removeConsoletransform-remove-consolefalse
removeDebuggertransform-remove-debuggerfalse
removeUndefinedtransform-remove-undefinedtrue
replaceminify-replacetrue
simplifyminify-simplifytrue
simplifyComparisonstransform-simplify-comparison-operatorstrue
typeConstructorsminify-type-constructorstrue
undefinedToVoidtransform-undefined-to-voidtrue

相同的参数传递给多个插件

  • 当多个插件需要相同的参数时,在一个地方声明更容易控制。然后将这些参数传递给两个或多个插件。
参数名插件
keepFnNamePassed to mangle & deadcode
keepClassNamePassed to mangle & deadcode
tdzPassed to builtIns, evaluate, deadcode, removeUndefined

示例

babel.config.json
{
"presets": [["minify", {
"evaluate": false,
"mangle": true
}]]
}
babel.config.json
{
"presets": [["minify", {
"mangle": {
"exclude": ["ParserError", "NetworkError"]
}
}]]
}
babel.config.json
{
"presets": [["minify", {
"keepFnName": true
}]]
}
// is the same as
{
"presets": [["minify", {
"mangle": {
"keepFnName": true
},
"deadcode": {
"keepFnName": true
}
}]]
}

You can read more about configuring preset options here