Babel plugin for automatic React display name generation with tree-shaking and prefix support, forked from @zendesk/babel-plugin-react-displayname
npm install @probablyup/babel-plugin-react-displayname> Automatically generate display names for React components, while retaining tree-shaking support in bundlers.
1. Install the dependency
``sh`
yarn add --dev @probablyup/babel-plugin-react-displayname
2. Add the plugin to your babel configuration
`json`
{
"plugins": ["@probablyup/babel-plugin-react-displayname"]
}
Why use this?
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:
`tsx
const Linebreak = React.memo(() => {
return
;
});
const Img = function () {
return ;
}
`
into:
`tsx
const Linebreak = React.memo(function _Linebreak() {
return
;
});
Linebreak.displayName = "Linebreak";
const Img = function () {
return ;
};
Img.displayName = "Img";
`
Object., defaults to { "react": ["createContext"] }
Enables generation of displayNames for certain called functions.
`json`
{
"plugins": ["@probablyup/babel-plugin-react-displayname", {
"allowedCallees": {
"react": ["createComponent"]
}
}]
}
#### Example
By default, with allowedCallees set to { "react": ["createContext"] }:
`tsx`
import React, { createContext } from 'react';
const FeatureContext = createContext();
const AnotherContext = React.createContext();
is transformed into:
`tsx`
import React, { createContext } from 'react';
const FeatureContext = createContext();
FeatureContext.displayName = "FeatureContext";
const AnotherContext = React.createContext();
AnotherContext.displayName = "AnotherContext";
Allows for rudimentary templating with the generated displayName. For example:
`json`
{
"plugins": ["@probablyup/babel-plugin-react-displayname", {
"template": "DS.%s",
}]
}
#### Example
from:
`tsx
const Linebreak = React.memo(() => {
return
;
});
const Img = function () {
return ;
}
`
to:
`tsx
const Linebreak = React.memo(function _Linebreak() {
return
;
});
Linebreak.displayName = "DS.Linebreak";
const Img = function () {
return ;
};
Img.displayName = "DS.Img";
``