Xun Yang
Xun Yang

Reputation: 4419

Webpack, babel and react: Remove certain classnames from production build

In my project I use a special type of classNames starting with 'u-', e.g. 'u-title_bar', for unit tests. I'd like to remove them from the production build, is there a tool for doing that?

// MyComponent.jsx
// u-my_comp is just for unit testing. my_comp is for styling
const MyComponent = () => <div className="u-my_comp my_comp">My Component</div>

// MyComponent.test.jsx
expect(myComponent.find('.u-my_comp).text()).toEqual('My Component');

// Expected result after cleanup: 
<div className="my_comp">My Component</div>

Upvotes: 1

Views: 537

Answers (1)

Estus Flask
Estus Flask

Reputation: 222474

It would be possible to detect these class names only with custom Babel transform, and it would fail for dynamic class names.

In case it's needed to remove all u- classes, a helper should be created:

const prodClassNames = (...classNames) => classNames
  .reduce((classNames, className) => classNames.concat(className.split(/\s+/)), [])
  .filter(className => process.env.NODE_ENV !== 'production' || !/^u-/.test(className))
  .join(' ');

Can be used as:

<div className={prodClassNames('u-my_comp my_comp')}>My Component</div>

Or:

<div className={prodClassNames('u-my_comp', 'my_comp')}>My Component</div>

Upvotes: 3

Related Questions