Automatically generate display names for React components
Internal usage:
yarn add @gadget-inc/babel-plugin-react-displayname
Public usage: Copy src/index.js
to a local file
@gadget-inc/babel-plugin-react-displayname: "file:../path/to/file"
React dev tools infer component names from the name of the function or class that defines the component. However, it does not work when anonymous functions are used.
This plugin fixes that by automatically generating the displayName property for assigned anonymous functions.
This plugin converts the following:
const Linebreak = React.memo(() => {
return <br/>;
});
const Img = function () {
return <img/>;
}
into:
const Linebreak = React.memo(function _Linebreak() {
return <br />;
});
Linebreak.displayName = "Linebreak";
const Img = function () {
return <img />;
};
Img.displayName = "Img";
Using npm:
npm install --save-dev @gadget-inc/babel-plugin-react-displayname
or using yarn:
yarn add @gadget-inc/babel-plugin-react-displayname --dev
Without options:
{
"plugins": ["@gadget-inc/babel-plugin-react-displayname"]
}
With options:
{
"plugins": ["@gadget-inc/babel-plugin-react-displayname", {
"allowedCallees": {
"react": ["createComponent"]
}
}]
}
Object.<string, string[]>
, defaults to { "react": ["createContext"] }
Enables generation of displayNames for certain called functions.
By default, with allowedCallees
set to { "react": ["createContext"] }
:
import React, { createContext } from 'react';
const FeatureContext = createContext();
const AnotherContext = React.createContext();
is transformed into:
import React, { createContext } from 'react';
const FeatureContext = createContext();
FeatureContext.displayName = "FeatureContext";
const AnotherContext = React.createContext();
AnotherContext.displayName = "AnotherContext";