babel/babel

[Bug]: Fragment child elements are not transformed correctly when using @babel/plugin-transform-react-constant-elements

mo36924 opened this issue · 2 comments

💻

  • Would you like to work on a fix?

How are you using Babel?

Programmatic API (babel.transform, babel.parse)

Input code

const a = () => <><div>a</div></>

Configuration file name

babel.config.json

Configuration

{
  "parserOpts": {
    "plugins": ["jsx"]
  },
  "presets": [],
  "plugins": ["@babel/plugin-transform-react-constant-elements"]
}

Current and expected behavior

Expected:

var _div;
const a = () => <>{_div || (_div = <div>a</div>)}</>;

or

var _Fragment;;
const a = () => _Fragment || (_Fragment = <><div>a</div></>);

Received:

var _div;
const a = () => <>_div || (_div = <div>a</div>)</>;

Environment

  • System:
    OS: macOS 14.4.1
  • Binaries:
    Node: 20.11.1 - ~/.proto/shims/node
    Yarn: 1.22.19 - ~/.nvm/versions/node/v18.18.2/bin/yarn
    npm: 10.2.4 - ~/.proto/shims/npm
    bun: 1.0.29 - ~/.proto/shims/bun
  • npmPackages:
    @babel/plugin-transform-react-constant-elements: ^7.24.1 => 7.24.1
    @babel/preset-typescript: ^7.24.1 => 7.24.1

Possible solution

if (
path.parentPath.isJSXElement() ||
path.parentPath.isJSXAttribute()
) {
replacement = t.jsxExpressionContainer(replacement);
}

Although the entire fragment cannot be made constant, the transformation of child elements works fine using the code below.

if (
  path.parentPath.isJSXFragment() ||
  path.parentPath.isJSXElement() ||
  path.parentPath.isJSXAttribute()
) {
  replacement = t.jsxExpressionContainer(replacement);
}

Additional context

No response

Hey @mo36924! We really appreciate you taking the time to report an issue. The collaborators on this project attempt to help as many people as possible, but we're a limited number of volunteers, so it's possible this won't be addressed swiftly.

If you need any help, or just have general Babel or JavaScript questions, we have a vibrant Slack community that typically always has someone willing to help. You can sign-up here for an invite.

Do you want to open a PR with that proposed fix? It looks good to me :)