Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove html attribute in production build

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?

like image 950
per_jansson Avatar asked May 12 '17 09:05

per_jansson


2 Answers

There are a few babel plugins that might fit the bill for this:

  • babel-plugin-react-remove-properties
  • babel-plugin-remove-attribute
  • babel-plugin-remove-object-properties

Edit from comments

Attributes are automatically ignored if their value is undefined. You can use that to your advantage and use some kind of configuration (possibly process.env.NODE_ENV?) and a Higher-Order Component to set a prop for the data-app-feature value only if not in production.

HOC

const appFeature = (Component, appFeature) => (props) => {
  const isRunningInProduction = configuration.isProduction // or however you want to set this
  return <Component appFeature={ isRunningInProduction ? appFeature : undefined } {...props}  />
}

Component

const ExampleComponent = ({appFeature}) => {
  return <div class="Component__item___2jdnc" data-app-feature={appFeature}></div>
}

export default appFeature(ExampleComponent, "example-id")
like image 157
Michael Peyper Avatar answered Oct 06 '22 06:10

Michael Peyper


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.

  • babel-plugin-remove-object-properties
  • babel-plugin-remove-attribute
like image 31
Mr_Perfect Avatar answered Oct 06 '22 05:10

Mr_Perfect