删除生产版本中的html属性

per*_*son 8 reactjs webpack

为了能够为我们的Webpack构建的React应用程序编写Selenium测试用例,我们将data-*属性添加到HTML元素的某些部分,例如:

<div class="Component__item___2jdnc" data-app-feature="example-id"></div>
Run Code Online (Sandbox Code Playgroud)

我们可以使用它们来定位要与之交互并断言的元素.但是,在生产环境中,我希望将它们删除.怎么可能实现?

Mr_*_*ect 9

这个答案纯粹适用于使用 webpack 进行应用程序的生产/开发构建的人。在webpack.prod.config 中执行以下操作。在webpack.dev.config 中忽略

  • 通过运行安装插件 npm installbabel-plugin-react-remove-properties
  • 在babel loader配置中添加如下

      {
        test: /\.(js|jsx)$/,
        use: [{
          loader: 'babel-loader',
          options: {
            plugins: [
              ["react-remove-properties", {"properties": ["data-test-id"]}]
            ]
          }
        }],
        exclude: /node_modules/,
      }
    
    Run Code Online (Sandbox Code Playgroud)
  • data-test-id是我们将在 selenium 测试用例中用于获取元素的属性。根据问题,它是data-app-feature

我们可以使用以下插件做同样的事情。


Mic*_*per 8

有一些babel插件可能符合这个要求:


从评论中编辑

如果属性值为,则会自动忽略属性undefined.您可以使用它来获得优势,并使用某种配置(可能process.env.NODE_ENV?)和高阶组件,data-app-feature只有在不生产时才为该值设置支柱.

HOC

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

零件

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

export default appFeature(ExampleComponent, "example-id")
Run Code Online (Sandbox Code Playgroud)


小智 5

我在使用时遇到了同样的问题styled-components。我发现这是最直接的解决方案,无需使用 HOC 或 Babel 插件。

我创建了一个函数,它检查特定环境,然后返回传递给它的值,或者undefined. 如果属性值为 ,则undefined不会包含该属性。

export const ifDev = val => (process.env.NODE_ENV === "development" ? val : undefined);
Run Code Online (Sandbox Code Playgroud)

然后在你的组件中:

import { ifDev } from './dev';

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

现在,我可以在使用生成的类名的同时在浏览器测试中找到元素,并且这些属性不会包含在生产版本中。