Control/Customize Component name minification in Production React

Viewed 676

Background

I often use "React Developer Tools" to understand the component structure of various website that I like and take inspiration from. Though, lot of websites have random names for the components, few websites have distinguishable names which can be helpful for aspiring React Developers or hobbyists. One such website is https://www.joshwcomeau.com. Below is a screenshot from one of the pages in his website. The name of few of the components explains itself what it is going to render. And since this is his blog, where he talks about various tips and tricks for React Development, it becomes helpful to have a look at this.

Question

Now when I develop a website using create-react-app(CRA), all my component names are minified to a couple of random letters by Webpack. How can I control this behavior?

Note: My main question is - How to control this behavior in any React application (not just CRA). I know that Josh uses Next.js for his blog, so does any framework like Gatsby, Next etc... provide control over this?.

Note:

  • I'm aware that the component names are visible in development mode, but I would like it to be visible in production too (for the reason explained above in "Background").
  • I'm aware that webpack can generate "sourcemap" but doing that would expose my entire code structure. So I prefer not to use sourcemaps
Screenshot of Josh's Website Screenshot of My Website
React Devtools from joshwcomeau.com React Devtools from my website
1 Answers

You can achieve this with a third party library:

From webpack-react-component-name documentation:

Normally React component names are minified during compilation. This plugin makes these component names available in production bundles by hooking into Webpack's compilation process, traversing the AST looking for React component definitions and updating the emitted source code to populate the displayName property. This is the property that, when populated, is used by the React Dev Tools extension to determine the name of a component.

So you can install this webpack plugin with:

npm install webpack-react-component-name -save-dev

once it is installed, add the plugin to the plugins list in webpack configs:

  plugins: [
    new WebpackReactComponentNamePlugin()
  ],
Related