Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
1 task
mo36924 opened this issue Apr 26, 2024 · 2 comments
Labels

Comments

@mo36924
Copy link

mo36924 commented Apr 26, 2024

馃捇

  • 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

@babel-bot
Copy link
Collaborator

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.

@nicolo-ribaudo
Copy link
Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants