Skip to content

gadget-inc/babel-plugin-react-displayname

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@gadget-inc/babel-plugin-react-displayname

Jest test CI

Automatically generate display names for React components

Installation

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"

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.

What does it do?

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";

Install

Using npm:

npm install --save-dev @gadget-inc/babel-plugin-react-displayname

or using yarn:

yarn add @gadget-inc/babel-plugin-react-displayname --dev

Usage

With a configuration file (Recommended)

Without options:

{
  "plugins": ["@gadget-inc/babel-plugin-react-displayname"]
}

With options:

{
  "plugins": ["@gadget-inc/babel-plugin-react-displayname", {
    "allowedCallees": {
      "react": ["createComponent"]
    }
  }]
}

Options

allowedCallees

Object.<string, string[]>, defaults to { "react": ["createContext"] }

Enables generation of displayNames for certain called functions.

Example

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";

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages