当前位置: 首页 > 文档资料 > Babel 中文文档 >

babel-preset-minify

优质
小牛编辑
127浏览
2023-12-01

安装

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

用法

Via .babelrc 配置文件(推荐)

.babelrc

{
  "presets": ["minify"]
}

或通过参数设置 -

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

通过命令行工具(CLI)

babel script.js --presets minify

通过 Node API

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

参数

有两种类型的参数:

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

通过插件一比一地映射

  • false - 关闭插件
  • true - 开启插件
  • { ...pluginOpts } - 开启插件并将 pluginOpts 传递给插件
参数名 插件 默认值
booleans transform-minify-booleans true
builtIns minify-builtins true
consecutiveAdds transform-inline-consecutive-adds true
deadcode minify-dead-code-elimination true
evaluate minify-constant-folding true
flipComparisons minify-flip-comparisons true
guards minify-guarded-expressions true
infinity minify-infinity true
mangle minify-mangle-names true
memberExpressions transform-member-expression-literals true
mergeVars transform-merge-sibling-variables true
numericLiterals minify-numeric-literals true
propertyLiterals transform-property-literals true
regexpConstructors transform-regexp-constructors true
removeConsole transform-remove-console false
removeDebugger transform-remove-debugger false
removeUndefined transform-remove-undefined true
replace minify-replace true
simplify minify-simplify true
simplifyComparisons transform-simplify-comparison-operators true
typeConstructors minify-type-constructors true
undefinedToVoid transform-undefined-to-void true

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

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

示例

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