I am following this Article to bundle my react app as a single js file that can be embedded as a widget into any website
Here is a redacted version of my package.json file showcasing the build scripts
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"build:widget": "parcel build src/index.js --no-source-maps -d widget" //This
}
So, on running yarn build:widget, I want parcel to build the entire App into a single index.js file that I can embed in a regular html file.
The build worked, but the only issue now is that I am getting the error ReferenceError: React is not defined after referencing the output index.js file inside my index.html file as shown below
<body>
<p>Hello World</p>
<div id="widget-section"></div>
</body>
<link href="../index.css" rel="stylesheet" />
<script src="../index.js"></script> //ReferenceError: React is not defined gets thrown here
Is there a better work around to this?
Even if your JavaScript does not explicitly call React i.e. import React from "react", you still need to add this import if you are using JSX. This is due to your JSX transpiler inlining JSX as React.createElement calls.