Skip to content

Suggestion: transforming jsx to jsx-runtime without createElement fallback #20031

Closed as not planned

Description

@morlay

Current code transform rule is not friendly for custom jsx-runtime or react-like lib.

// have to re export the `createElement`
import { createElement } from "@emotion/core"

import { jsx, jsxs, Fragment } from "@emotion/core/jsx-runtime"

Could we follow rules like below, could got same behavior.

  • <span key={key} {...obj} /> => jsx("span", obj, key)
  • <span {...obj} key={key} /> => jsx("span", {...obj, key}, key)

babel/babel#12177
microsoft/TypeScript#39199

Activity

  1. added
    Status: Unconfirmed
    on Oct 15, 2020
  2. gaearon commented on Oct 15, 2020

    @gaearon
    Collaborator

    I struggle to understand the issue — could you please write a more detailed description? I understand that the transform (intentionally) falls back to createElement but I don’t have a good sense of why this creates a problem for Emotion.

  3. morlay commented on Oct 15, 2020

    @morlay
    Author

    When using babel-transform-react-jsx with runtime: automatic,
    and set @jsxImportSource to switch custom jsx-runtime

    But if the fallback exists. codes transformed like below.

    // @jsxImportSource @emotion/core
    
    <span {...obj} key={key} />
    
    // convert to
    
    import { createElement } from "@emotion/core"
    
    createElement("span", { ...obj, key: key })

    and the createElement need to export by @emotion/core too (is this necessary?).
    For support key after object spread (if not do this, transformed codes will got createElement not found).

    now @emotion/core have as createElement-like api named jsx,
    but @jsx jsx and @jsxImportSource could be set at same time.
    but @jsx jsx and @jsxImportSource could not be set at same time.

    I think add a custom jsx-runtime should only foucs @emotion/core/jsx-runtime with exports jsx,jsxs, Fragment

    @gaearon What do you think?

  4. Andarist commented on Oct 15, 2020

    @Andarist
    Contributor

    but @jsx jsx and @jsxImportSource could be set at same time.

    can they? arent they mutually exclusive?

    I think add a custom jsx-runtime should only foucs @emotion/core/jsx-runtime with exports jsx,jsxs, Fragment

    That would be IMHO preferable as well, but I guess there are good reasons why this is required right now and we'd just have to add export { jsx as createElement } from './jsx' to those new entry points, so it ain't bad. Although probably not having to worry about createElement would allow us to cut a few bundlesize bytes.

    Was this fallback in the original Babel's PR? I must have missed it there as I was following that PR rather closely. Couldn't spread operator or an Object.assign call be inserted instead of falling back to createElement?

    EDIT:// Oh, I have just now realized that createElement is supposed to be exported from the jsxImportSource itself and not from those new jsx-related entrypoints. I find this quite weird as well and if it's required to provide a separate @jsx pragma for this case like in this TS playground (it uses React.createElement even though @jsxImportSource is provided) then this is quite a big usability issue from Emotion's PoV.

  5. gaearon commented on Oct 15, 2020

    @gaearon
    Collaborator

    I'm struggling to parse the discussion on this issue so I would really appreciate if you could rephrase this imagining that I know very little about the JSX transform. All of the comments are written in a very terse way so far.

    Here's what I understand so far:

    • <div key="x" {...spread} /> intentionally falls back to createElement because we can't know which key to use
    • Emotion should be able to have a createElement — but doesn't want to after the JSX changes?
      • Or is it that specifying both is a problem?

    The thing I struggle with is it's not obvious to me what exactly is the "usability issue" here. It's like something implied but I don't understand what it is.

  6. gaearon commented on Oct 15, 2020

    @gaearon
    Collaborator

    Maybe it would help to reframe in the sense of: (1) here's the source code, (2) here's the Babel config we tell Emotion users to apply, (3) here's how they have to write code because of this issue, (4) here's how we'd like them to write code instead. Or (5) here's what we have to expose to work around this problem, (6) here's what we would prefer to expose instead. Or (7) here's what configuration they have to specify to work around this, (8) here's the configuration we want them to use instead.

  7. Andarist commented on Oct 15, 2020

    @Andarist
    Contributor

    Sorry for being overly terse and losing the required context. I'll try to amend it now as well as I can.

    As you may know, Emotion has chosen to support the so-called css prop, and to make it work in a variety of use cases we have chosen to support it using a custom JSX pragma. We got a fair share of critique from the community for that as people like to bikeshed over this sort of thing and for some people having to use a magic comment (pragma) was too odd. We stand by the technical choices we've made and pros that it gives us - supporting 0config tools like CRA is important for us. However, after that critique from the community, we've caved a little bit and we've provided a way to insert that pragma on behalf of our consumers automatically in a form of a Babel plugin.

    So, currently, there are 2 ways of how one can use css prop API:

    1. writing pragma (/** @jsx jsx */ + import { jsx } from '@emotion/core')
    2. using @emotion/babel-preset-css-prop

    The jsx function that we provide is just a custom version of the createElement that either calls React.createElement if no css prop is given to it or it resolves it and then calls React.createElement using the rest of the props (the second part is a little bit simplified, but that's the gist of what it's doing).

    If we consider only the second way of adding support for the css prop then nothing really changes - it's already "automatic" from our side, so it's just a matter of adding support for those new entry points etc and it should just work. Note: this has never worked with just the TS compiler which is a real bummer as it doesn't allow people to set jsx pragma globally. I've hoped that this would change with the introduction of the new runtime but I got no comment back from the TS team when I've asked about this (more than once I believe).

    The problem is with the first way - writing pragma manually. I was sure that using /** @jsxImportSource @emotion/react */ would be enough to make it work. I can already hear people complaining about this new pragma (way longer than the previous one) but it is what it is - we need to support 0-config tools and TS compiler.

    Let's take a look at Babel:

    input
    // babelrc.js
    module.exports = {
      presets: ["@babel/preset-react"]
    }
    /** @jsxImportSource @emotion/react */
    
    <div {...props} />;
    
    <div {...props} key="key"/>;
    output
    function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
    
    /** @jsxImportSource @emotion/react */
    
    /*#__PURE__*/
    React.createElement("div", props);
    
    /*#__PURE__*/
    React.createElement("div", _extends({}, props, {
      key: "key"
    }));

    Result? It doesn't work - using @jsxImportSource is not enough, one has to provide a { runtime: "automatic" } to the React's preset to make it work. It's one more thing that has to be explained, documented etc. Arguably it's not that big of a deal as 0-config tools will probably already have this option provided automatically. Some people might get lost though when configuring stuff on their own and wanting to use the pragma approach, or just because they have skipped the section on how to add Emotion's Babel plugin, or for any other reason. It feels like a small detail but I don't quite see why a sole fact of using @jsxImportSource doesn't switch the transformer to the automatic one.

    Even if it works - it still requires createElement from the root of the importSource. I understand why React has to provide this (compat reasons) but the same scale and constraints do not apply to the rest ecosystem, parts of it (like Emotion) could "move" faster away from using createElement and thus saving on the implementation complexity and bundlesize of the library. Supporting this doesn't add that much to both of those - but if we could skip that entirely, why wouldn't we like to do it? It also imposes the same on other alternatives runtimes/libraries wanting to integrate with the new transform - it makes the integration more difficult, it's just one more thing to be aware of. If one sees the automatic runtime and jsx helpers the intuition (in most cases) will tell them that it's enough to make things work, but there is this special case with createElement that I feel is quite easy to miss.

    Let's take a look at TS now (note - I'm using TS online playground with nightly build that is available there):

    input
    /** @jsxImportSource @emotion/react */
    
    <div {...props} />;
    
    <div {...props} key="key"/>;
    output
    "use strict";
    /** @jsxImportSource @emotion/react */
    _jsx("div", Object.assign({}, props), void 0);
    React.createElement("div", Object.assign({}, props, { key: "key" }));

    This has not worked as expected at all. The createElement exception has been inserted as React.createElement. To make it work as expected one would have to use both pragmas and an explicit import for the @jsx right now:

    /** @jsxImportSource @emotion/react */
    /** @jsx jsx */
    import { jsx } from '@emotion/react'

    I can only assume now that this a bug in TS nightlies but it is IMHO an indication of how easy is to miss this case and implement it incorrectly. If this is about to stay (please no) then this is a huge DX downgrade for the TS users.

  8. gaearon commented on Oct 15, 2020

    @gaearon
    Collaborator

    The jsx function that we provide is just a custom version of the createElement that either calls React.createElement if no css prop is given to it or it resolves it and then calls React.createElement using the rest of the props (the second part is a little bit simplified, but that's the gist of what it's doing).

    Hmm, are you saying that Emotion provides jsx but it has no relation to React's concept of jsx because Emotion wanted a shorter synonym for createElement?

  9. gaearon commented on Oct 15, 2020

    @gaearon
    Collaborator

    Result? It doesn't work - using @jsxImportSource is not enough, one has to provide a { runtime: "automatic" } to the React's preset to make it work.

    I think it would work in Babel 8 since that the new transform will become the default one?

    It feels like a small detail but I don't quite see why a sole fact of using @jsxImportSource doesn't switch the transformer to the automatic one.

    Yeah, I'm not sure. Maybe because they're currently implemented as two completely separate transforms. Maybe @lunaruan or @sebmarkbage knows.

    Supporting this doesn't add that much to both of those - but if we could skip that entirely, why wouldn't we like to do it?

    I think the createElement case is part of the reason, as we need to keep supporting <div {...stuff} key="x" /> but the new JSX signature needs key as a separate argument. How do you propose to handle that instead? It's important to preserve the current spread semantics here, otherwise it would be a huge breaking change.

    In the longer run we want to make this pattern a compile error. But that would require some transitional period. If you have a custom Babel plugin you could make that a compile error today, but this doesn't help the zero-config case.

    This has not worked as expected at all. The createElement exception has been inserted as React.createElement

    You didn't show a successful example, but I think you're saying that Babel would instead produce code with two auto-imports rather than one. Is this correct? Does Babel have the "severe DX downgrade" aside from a longer pragma?

    I can only assume now that this a bug in TS nightlies but it is IMHO an indication of how easy is to miss this case and implement it incorrectly. If this is about to stay (please no)

    I don't understand the reasoning here. It does sound like a bug in TS, because it doesn't match the behavior in Babel and in our tests. If it's a bug in TS, it's only "about to stay" if you don't report it to TS and they don't fix it. So it seems like the next action item is to report it.

    I don't see why "easy to miss" is an important consideration here — it's only "easy to miss" once per JSX implementation. Today, we have two mainstream ones (Babel and TS). I think it's expected that transform implementations are nuanced. ES spec nuances are also easy to miss, but this doesn't preclude Babel from getting them right.

    Assuming the TS gets reported and fixed, is the "DX downgrade" still severe?

  10. morlay commented on Oct 15, 2020

    @morlay
    Author

    @gaearon

    My concern is why we need do the fallback.

    if we just want to pass key prop, i think

    <span {...obj} key={key} /> => jsx("span", {...obj, key}, key)

    could got same result with jsx-runtime

    Is there other reasons to fallack createElement (only for key after props spread, key before props spread already using jsx-runtime)?

    • <div key="x" {...spread} /> intentionally falls back to createElement because we can't know which key to use

    <div key="x" {...spread} /> not fallback.

    babel-config: { plugins: ["@babel/plugin-transform-react-jsx", { "runtime": "automatic" }]}

    <span {...props} key={"key-after"} />
    <span key={"key-before"} {...props} />
    
    // convert to 
    
    import { jsx as _jsx } from "react/jsx-runtime";
    import { createElement as _createElement } from "react";
        
     _createElement("span", { ...props,
          key: "key-after"
     })
    _jsx("span", { ...props }, "key-before")
  11. morlay commented on Oct 16, 2020

    @morlay
    Author

    @Andarist

    There is a point i confused - "only key after props spread do the fallback"

    /** @jsxImportSource @emotion/react */
    
    <div key="key "{...props} />;
    
    <div {...props} key="key"/>;
    
    // will convert to 
    
    import { createElement } from "@emotion/react"
    import { jsx } from "@emotion/react/jsx-runtime"
    
    jsx("div", props, "key")
    createElement("div", { ...props, key: "key" }) // only key after props spread do the fallback 

    i don't know why not convert to jsx("div", props, "key") for both cases.

    it could be jsx("div", { ...props, key: "key" }, "key")
    if want to pass key into component as babel/babel#12177 (comment) mentioned

  12. morlay commented on Oct 16, 2020

    @morlay
    Author

    I think the createElement case is part of the reason, as we need to keep supporting <div {...stuff} key="x" /> but the new JSX signature needs key as a separate argument. How do you propose to handle that instead? It's important to preserve the current spread semantics here, otherwise it would be a huge breaking change.

    @gaearon

    i still think <div {...stuff} key="x" /> transforming tojsx("div", stuff, "x") will not break anything (props.key is always undefined in Component ).

    However. current tools transforming <div {...stuffWithKeyProp} /> tojsx("div", { ...stuffWithKeyProp }),
    Which will cause the issue you mentioned. When user upgrade to jsx-runtime, key missing error will be throw.

  13. morlay commented on Oct 16, 2020

    @morlay
    Author

    By infomation from https://github.com/reactjs/rfcs/blob/createlement-rfc/text/0000-create-element-changes.md#deprecate-spreading-key-from-objects

    i think the transforming rules could be unified:

    • <div {...stuffWithKeyProp} /> => jsx("div", stuffWithKeyProp)
      • if key needed, warning key missing
    • <div key="key-before" {...stuff} /> => jsx("div", stuff, "key-before")
    • <div {...stuff} key="key-after" /> => jsx("div", stuff, "key-after")

    the key is the special prop as fact rule for a long time.
    still let it continue special until it renamed to @key

    even support @key too.
    if @key not exists, but key exists, show the deprecating warning and using key as fallback of @key, and do the merging.

    • <div @key="key-before" {...stuff} /> => jsx("div", { ...stuff }, "key-before")
      • <div key="key-before" {...stuff} /> => jsx("div", { key: "key-before", ...stuff }, "key-before")
    • <div {...stuff} @key="key-after" /> => jsx("div", { ..stuff }, "key-after")
      • <div {...stuff} key="key-after" /> => jsx("div", { ...stuff, key: "key-after" }, "key-after")
  14. ljharb commented on Oct 16, 2020

    @ljharb
    Contributor

    Considering that the last key prop (or any prop) should win, it’s very confusing that #20031 (comment) seems to be doing the exact opposite of what would be needed.

  15. morlay commented on Oct 16, 2020

    @morlay
    Author

    @ljharb you mean confusing for the current transforming results or my suggestion?

  16. 22 remaining items

  17. added
    Resolution: Stale
    on Jan 9, 2022
  18. iMrDJAi commented on Aug 6, 2022

    @iMrDJAi

    bump

  19. removed
    Resolution: Stale
    on Aug 6, 2022
  20. iMrDJAi commented on Aug 6, 2022

    @iMrDJAi

    The createElement fallback breaks compatibility and consensus. The "key" prop is React specific and should not be treated specially in the context of custom JSX runtimes. JSX meant to be a way to embed inline XML into JavaScript code. The current spec is broken and changes need to be done. It needs to consider that and completely separate React from JSX.

  21. ljharb commented on Aug 6, 2022

    @ljharb
    Contributor

    I don’t think appeals to “meant to” are going to help you here; jsx is “meant to” be used for React, it’s just become used more broadly.

  22. iMrDJAi commented on Aug 6, 2022

    @iMrDJAi

    @ljharb Yes, React was the reason of the popularity of JSX, however JSX was a thing even before its adoption by React (For example https://en.wikipedia.org/wiki/ECMAScript_for_XML).
    Since it become used more outside React, it's a good idea to make it more universal and less React specific, and most importantly, easier for other developers to customize.

  23. ljharb commented on Aug 6, 2022

    @ljharb
    Contributor

    @iMrDJAi the concept of "xml in JS" certainly was, but JSX, specifically, was created by the react team for use in react.

  24. iMrDJAi commented on Aug 10, 2022

    @iMrDJAi

    @ljharb Regardless of the origins of JSX, and the createElement fallback, I have managed to create my own custom runtime that transforms JSX into Non-Compact objects that can be converted into plain XML. 😅

    https://github.com/iMrDJAi/xml-jsx

  25. ljharb commented on Aug 10, 2022

    @ljharb
    Contributor

    @iMrDJAi congrats! I’m not saying at all that jsx should only be for react; I’m just saying an appeal to original intentions won’t help you :-)

  26. iMrDJAi commented on Aug 11, 2022

    @iMrDJAi

    @ljharb Regardless of the origins of JSX, and the createElement fallback, I have managed to create my own custom runtime that transforms JSX into Non-Compact objects that can be converted into plain XML. 😅

    https://github.com/iMrDJAi/xml-jsx

    Update: I have added docs and published the package under a different name: https://github.com/iMrDJAi/xml-jsx-runtime.
    It was really a fun experiment. :)

  27. github-actions commented on Apr 10, 2024

    @github-actions

    This issue has been automatically marked as stale. If this issue is still affecting you, please leave any comment (for example, "bump"), and we'll keep it open. We are sorry that we haven't been able to prioritize it yet. If you have any new additional information, please include it with your comment!

  28. added
    Resolution: Stale
    on Apr 10, 2024
  29. github-actions commented on Apr 17, 2024

    @github-actions

    Closing this issue after a prolonged period of inactivity. If this issue is still present in the latest release, please create a new issue with up-to-date information. Thank you!

  30. added a commit that references this issue on Jan 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Resolution: StaleStatus: Unconfirmed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      ⌂ Proxy