How to remove data-testid from production build
Asked Answered
U

4

6

I want to remove data-testid from the production build, so these attributes can't be found in the prod build Particularly in this case, I need something that works with .tsx files I know how to remove it using a function in components, but I think there should be a smarter way to do this. react cra react-app-rewired

Ullund answered 25/2, 2023 at 2:27 Comment(0)
S
13

I guess my question would be why do you think you need to remove them? They're just string attributes. Unless you're working on an app with an incredible number of elements with ID's and you want to decrease the build size by a very tiny amount, it's not particularly useful.

Unless you think these ID's are somehow providing potentially dangerous information to bad actors, I wouldn't be concerned about them. And if you think they are, the first thing I would do is reform their naming so that's not the case.

But if you are determined to remove them, there appears to be a Babel plugin that will strip them out when your code is transpiled: https://github.com/coderas/babel-plugin-jsx-remove-data-test-id

But in my personal opinion it's probably not necessary.

Cheers!

Sober answered 25/2, 2023 at 3:54 Comment(1)
Right or wrong, at least one other person is interested in removing testids: dpericich.medium.com/…Phylogeny
F
4

In case anyone coming here using Vite, there's a bunch of plugins which might work directly or could be used to take inspiration from

There's also a Rollup plugin that should work, which also modifies the AST

Note: haven't tried any of those myself so far ^^ though the AST approach should be "safer" to use

Faculty answered 21/12, 2023 at 4:17 Comment(0)
A
1

The options above work well with React, and for those who use Next.js you can use the code below as mentioned in the docs https://nextjs.org/docs/architecture/nextjs-compiler#remove-react-properties

In next.config.js add:

module.exports = {
   compiler: {
     reactRemoveProperties: { properties: ['^data-testid$'] },
   },
}
Abdullah answered 6/8, 2024 at 12:38 Comment(0)
L
0

In next.config.js add:

  const IS_DEV = process.env.NODE_ENV === "development";
  module.exports = {
  compiler: !IS_DEV
    ? {
          reactRemoveProperties: { properties: ["^data-testid$"] },
      }
    : {},  }

Note: This way in dev it still works, but in production the property won't be displayed.

Laundress answered 3/10, 2024 at 14:13 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.