I'm trying to run React in Babel-standalone and use import from nearby files.
I prefer not using a bundler for this, nor to use solutions that aren't import/export.
Here is a concise sample of the problem:
index.html:
<html>
<head>
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/[email protected]/babel.js"></script>
</head>
<body>
<div id="root-box"></div>
<script type="text/babel" data-type="module" data-presets="react">
import { Something } from "./Something.js";
ReactDOM.createRoot(document.getElementById("root-box")).render(
<Something />
);
</script>
</body>
</html>
Something.js
export const Something = () => {
return <div>Hello</div>
}
The resulting error is:
Uncaught SyntaxError: Unexpected token '<' (at Something.js:2:10)
which means that babel has obtained the other file, but did not transpile it.
CodePudding user response:
I think there are two issues here. Firstly you are not including Something.js in your script sources to be compiled by Babel. Secondly the UMD modules transform is not being applied, preventing the import from working correctly. Therefore, a working version of your code looks like this.
<html>
<head>
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/[email protected]/babel.js"></script>
<script data-plugins="transform-modules-umd" type="text/babel" data-presets="react" data-type="module" src="Something.js"></script>
</head>
<body>
<div id="root-box"></div>
<script data-plugins="transform-modules-umd" type="text/babel" data-presets="react" data-type="module">
import { Something } from "./Something.js";
ReactDOM.createRoot(document.getElementById("root-box")).render(
<Something />
);
</script>
</body>
</html>