Remove html attribute in production build

Viewed 12464

In order to be able to write Selenium test cases for our Webpack built React app we've added data-* attributes to certain parts of the HTML elements, example:

<div class="Component__item___2jdnc" data-app-feature="example-id"></div>

We can use these to locate elements to interact with and assert on. But, in production environment I would like to have them removed. How could that be achieved?

5 Answers

This answer is purely for the people who use webpack for production/development builds of the application. Do the following in webpack.prod.config. Ignore in webpack.dev.config

  • Install plugin by running npm installbabel-plugin-react-remove-properties
  • Add it in babel loader configuration as follows

      {
        test: /\.(js|jsx)$/,
        use: [{
          loader: 'babel-loader',
          options: {
            plugins: [
              ["react-remove-properties", {"properties": ["data-test-id"]}]
            ]
          }
        }],
        exclude: /node_modules/,
      }
    
  • data-test-id is the attribute we are going to use in selenium test cases to get the elements. According to the question, it is data-app-feature

The same thing we can do using below plugins.

I ran into the same issue while using styled-components. This is the solution I found to be most straight forward to me without using a HOC or Babel plugins.

I created a function which checks for a specific environment and then returns the value you pass to it, or undefined. If the attribute value is undefined the attribute wont be included.

export const ifDev = val => (process.env.NODE_ENV === "development" ? val : undefined);

Then in your components:

import { ifDev } from './dev';

<div className="sc-fMiknA" data-app-feature={ifDev("element-id")}></div>

Now I can find elements in browser tests while using generated class names and the attributes won't be included in production builds.

Related