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
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!
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
- l-mbert/vite-plugin-react-remove-attributes (modifies the
AST
, also works with Vue when used with JSX, might work in other JSX codebases as well) - mustafadalga/remove-attr (uses Regex)
- cogor/vite-plugin-vue-remove-attributes (uses String.replaceAll)
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
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$'] },
},
}
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.
© 2022 - 2025 — McMap. All rights reserved.