Skip to content

Latest commit

 

History

History
103 lines (82 loc) · 2 KB

File metadata and controls

103 lines (82 loc) · 2 KB

babel-plugin-transform-react-default-props

Transform React component’s defaultProps

Quickstart

yarn
yarn build

babel.config.js

const React = require('react');

const DeleteLogo = () => {
  return React.createElement('div', null, '✕');
};


module.exports = function () {
  return {
    "plugins": [
      ["./lib/index.js", {
        "config": {
          "Icon": {
            "width": 32,
            "height": 32,
            "color": "#dcdcdc"
          },
          "Input": {
            "fontSize": 16,
            "codes": ["+420", "+421"],
            "Delete": DeleteLogo
          }
        }
      }]
    ]
  }
};

Motivation

babel-plugin-transform-react-default-props is an easy and convenient way of overriding component's default props with your own without the need to re-export it.

And it's a build-time transformation so it should save some bytes and nanoseconds (in theory 😅) when compared to run-time alternatives.

Example

Input

class ClassDeclarationComponentWithStaticClassProperty extends React.Component {
  static defaultProps = {
    propToBeChanged: "propToBeChanged",
    propToRemainUnchanged: "propToRemainUnchanged",
  };
  render() {
    return <div />;
  }
}

Babel Plugins Config

  "plugins": [
    ["../lib/index.js", {
      "config": {
        "ClassDeclarationComponentWithStaticClassProperty": {
          "propToBeChanged": "changedProp",
          "propToBeAdded": "addedProp"
        }
      }
    }]
  ]

Output

class ClassDeclarationComponentWithStaticClassProperty extends React.Component {
  static defaultProps = {
    propToBeChanged: "changedProp",
    propToRemainUnchanged: "propToRemainUnchanged",
    propToBeAdded: "addedProp",
  };
  render() {
    return <div />;
  }
}

TODO

defaultProps are deprecated for functional components and this plugin should transform default function parameters as well.

License

Dual CC0 and MIT.