How do I import JSX to an HTML page via the <script> tag?

Viewed 79

I'm trying to figure out why my browser can't parse JSX, and how to configure my script tags so that it can.

The context: I'm creating a webpage that incorporates a Swagger-UI display, and using their documentation for embedding within html and adding custom plugins, I've got the following html, including a renderer script of type text-babel:

<div id="swagger-ui"></div>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/javascript" src="js/swagger-ui-bundle.js" charset="UTF-8"></script>


</script>
<script id="swagger-ui-renderer" type="text/babel">
  window.onload = function() {

    const MyOperationsPlugin = function(system) {
      return {
        wrapComponents: {
          OperationTag: (Original, system) => (props) => {
            props.tag = "MyValue"
            return <Original {...props}/>
          }
        }
      }
    }

  const ui = SwaggerUIBundle({
    url: "www.example-swagger.com",
    dom_id: '#swagger-ui',
    presets: [
      SwaggerUIBundle.presets.apis
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl,
      MyOperationsPlugin
    ],
  })

  window.ui = ui
}
</script>

This works great. Here's the problem: as I add more custom functionality, I want plugins to be in their own scripts. However, when I move myOperationsPlugin into its own file, myOperationsPlugin.js, and import it below my existing script tags...

<script type="text/javascript" src="js/myOperationsPlugin.js" charset="UTF-8"> </script>

...my browser complains about Unexpected token '<' when trying to parse <Original {...props}/>. Could someone suggest a way of structuring my JS and HTML such that I can write JSX in external files and import them?

Importing the script with type="text/babel" doesn't fix the problem, unfortunately.

1 Answers

You cannot use JSX tags in plain JavaScript.

Since there's just one JSX tag in your code

return <Original {...props}/>

you can replace it with non-JSX equivalent:

return system.React.createElement(Original, props)

In case of more complex code, there are other options but all of them involve converting JSX into the corresponding plain JS/HTML. You could also package your JSX-based plugin as an npm module like done here and load the compiled version through npm.

Related