@babel/plugin-transform-parameters

parameters - 图1info

This plugin is included in @babel/preset-env

This plugin transforms ES2015 parameters to ES5, this includes:

  • Destructuring parameters
  • Default parameters
  • Rest parameters

Examples

In

JavaScript

  1. function test(x = "hello", { a, b }, ...args) {
  2. console.log(x, a, b, args);
  3. }

Out

JavaScript

  1. function test() {
  2. var x =
  3. arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "hello";
  4. var _ref = arguments[1];
  5. var a = _ref.a,
  6. b = _ref.b;
  7. for (
  8. var _len = arguments.length,
  9. args = Array(_len > 2 ? _len - 2 : 0),
  10. _key = 2;
  11. _key < _len;
  12. _key++
  13. ) {
  14. args[_key - 2] = arguments[_key];
  15. }
  16. console.log(x, a, b, args);
  17. }

Installation

  • npm
  • Yarn
  • pnpm
  1. npm install --save-dev @babel/plugin-transform-parameters
  1. yarn add --dev @babel/plugin-transform-parameters
  1. pnpm add --save-dev @babel/plugin-transform-parameters

Caveats

Default parameters desugar into let declarations to retain proper semantics. If this is not supported in your environment then you’ll need the @babel/plugin-transform-block-scoping plugin.

Usage

babel.config.json

  1. {
  2. "plugins": ["@babel/plugin-transform-parameters"]
  3. }

Via CLI

Shell

  1. babel --plugins @babel/plugin-transform-parameters script.js

Via Node API

JavaScript

  1. require("@babel/core").transformSync("code", {
  2. plugins: ["@babel/plugin-transform-parameters"],
  3. });

Options

loose

boolean, defaults to false.

In loose mode, parameters with default values will be counted into the arity of the function. This is not spec behavior where these parameters do not add to function arity.

parameters - 图2caution

Consider migrating to the top level ignoreFunctionLength assumption.

babel.config.json

  1. {
  2. "assumptions": {
  3. "ignoreFunctionLength": true
  4. }
  5. }

Under the ignoreFunctionLength assumption, Babel will generate a more performant solution as JavaScript engines will fully optimize a function that doesn’t reference arguments. Please do your own benchmarking and determine if this option is the right fit for your application.

JavaScript

  1. // Spec behavior
  2. function bar1(arg1 = 1) {}
  3. bar1.length; // 0
  4. // ignoreFunctionLength: true
  5. function bar1(arg1 = 1) {}
  6. bar1.length; // 1

parameters - 图3tip

You can read more about configuring plugin options here