@babel/plugin-transform-parameters

This plugin transforms ES2015 parameters to ES5, this includes:

  • Destructuring parameters
  • Default parameters
  • Rest parameters

Examples

In

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

Out

  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

  1. npm install --save-dev @babel/plugin-transform-parameters

Caveats

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

Usage

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

Via CLI

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

Via Node API

  1. require("@babel/core").transform("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.

The loose implementation is 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.

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

You can read more about configuring plugin options here