Skip to content

[Bug]: @babel/preset-react inserts jsx-runtime after existing comments, which means they can be lost when bundling #15156

@TomStrepsil

Description

@TomStrepsil

💻

  • Would you like to work on a fix?

How are you using Babel?

@rollup/plugin-babel

Input code

See REPL (must manually select "automatic" react runtime)

import "react";

/* test comment */
const Foo = () => <div></div>;

export default Foo;

Configuration file name

babel.config.json

Configuration

{
  "presets": [
    ["@babel/preset-react", { "runtime": "automatic" }]
  ]
}

Current and expected behavior

Expected:

import "react";
import { jsx as _jsx } from "react/jsx-runtime";

/* test comment */
const Foo = () => /*#__PURE__*/_jsx("div", {});
export default Foo;

Received:

import "react";

/* test comment */
import { jsx as _jsx } from "react/jsx-runtime";
const Foo = () => /*#__PURE__*/_jsx("div", {});
export default Foo;

I would expect the input comment to remain above the Foo function, rather than have the react/jsx-runtime import interleaved.

The changed order causes rollup to remove the comment, for sanctity of tree-shaking. Please see issue raised with rollup for context.

N.B. When preset-env is enabled, the imports/comments are in the correct order:

"use strict";

exports.__esModule = true;
exports.default = void 0;
require("react");
var _jsxRuntime = require("react/jsx-runtime");
/* test comment */
const Foo = () => /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {});
var _default = Foo;
exports.default = _default;

Environment

@babel/core: 7.14.6
@babel/preset-react: 7.18.6
MacOS Monterey
Node 18.x

Possible solution

...will see what I can do...

Additional context

Perhaps needs a fixture added here?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions