@babel/plugin-transform-parameters
資訊
此外掛程式包含在 @babel/preset-env
中
此外掛程式將 ES2015 參數轉換為 ES5,其中包括
- 解構參數
- 預設參數
- Rest 參數
範例
在
JavaScript
function test(x = "hello", { a, b }, ...args) {
console.log(x, a, b, args);
}
輸出
JavaScript
function test() {
var x =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "hello";
var _ref = arguments[1];
var a = _ref.a,
b = _ref.b;
for (
var _len = arguments.length,
args = Array(_len > 2 ? _len - 2 : 0),
_key = 2;
_key < _len;
_key++
) {
args[_key - 2] = arguments[_key];
}
console.log(x, a, b, args);
}
安裝
- npm
- Yarn
- pnpm
npm install --save-dev @babel/plugin-transform-parameters
yarn add --dev @babel/plugin-transform-parameters
pnpm add --save-dev @babel/plugin-transform-parameters
注意事項
預設參數會簡化為 let
宣告,以保留適當的語意。如果您的環境不支援此功能,則您需要 @babel/plugin-transform-block-scoping 外掛程式。
用法
使用設定檔 (建議)
babel.config.json
{
"plugins": ["@babel/plugin-transform-parameters"]
}
透過 CLI
Shell
babel --plugins @babel/plugin-transform-parameters script.js
透過 Node API
JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-parameters"],
});
選項
loose
布林值
,預設為 false
。
在寬鬆模式下,具有預設值的參數會計入函式的 arity。這不是規範行為,其中這些參數不會增加函式 arity。
注意
考慮遷移至頂層 ignoreFunctionLength
假設。
babel.config.json
{
"assumptions": {
"ignoreFunctionLength": true
}
}
在 ignoreFunctionLength
假設下,Babel 會產生效能更高的解決方案,因為 JavaScript 引擎會完全最佳化不參照 arguments
的函式。請自行執行基準測試並確定此選項是否適合您的應用程式。
JavaScript
// Spec behavior
function bar1(arg1 = 1) {}
bar1.length; // 0
// ignoreFunctionLength: true
function bar1(arg1 = 1) {}
bar1.length; // 1
提示
您可以在 這裡 閱讀有關設定外掛選項的更多資訊