'configuring esbuild with react (replacing create-react-app)
I have a bunch of files with the extension js instead of jsx. (This is a react project).
I setup my package.json for build with such script:
"build": "esbuild src/App.js --bundle --minify --sourcemap --outfile=public/bundle.js",
Upon running it, I have tons of errors all complaining about js syntax such as:
const App = () => {
return (
<>
// some code
</>
)
}
where:
> src/App.js:16:2: error: Unexpected "<"
16 │ <>
╵ ^
This is a similar error for many files that have basic div's as return: <div> // content </div> stating that the < in the begging of the div is unexpected. I assume this is because it's not viewing these files as jsx. Is there some sort of flags I can set that will solve this? Changing every single file to a jsx is going to be a mission.
Solution 1:[1]
This can also happen when you forget to add the import directive [for the React library] to your component files.
For example, let's say you have a React app with the following structure:
.
+-- index.html
+-- index.js
+-| src
+-- app.js
+-| components
+-- my-component.js
+-| dist
+-- bundle.js
And the following file contents:
<!-- index.html -->
<html>
<head>
<title>My React App</title>
</head>
<body>
<div id="root"></div>
<script src="dist/bundle.js"></script>
</body>
</html>
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './src/app';
ReactDOM.render(
<React.StrictMode>
<App/>
</React.StrictMode>,
document.querySelector('#root')
);
// ./src/app.js
import Banner from './components/my-component';
function App() {
return (
<div className="App">
<header className="App-header">
<h1>Hello World</h1>
</header>
<main>
<Banner/>
</main>
</div>
);
}
export default App;
// .src/components/my-component.js
function MyBanner(){
return (
<h3>My Banner!</h3>
);
}
export default MyBanner;
To bundle your React app with ESBuild, you may be running something like this:
npx esbuild index.js --bundle --loader:.js=jsx --out-file=./dist/bundle.js
Note: You can use
npx esbuildinstead of./node_modules/.bin/esbuildif your npm version is 5.2.0 or higher.
After the build is complete, and you open index.html [in the browser], you should get an error saying React is not defined.
The reason for this is that in ./src/app.js and ./src/components/my-component.js, there is no import directive for React. So when the JSX is converted to React.createElement during the build process, there is no declared and accessible reference to React when your bundle executes in the browser; hence the error.
To fix this, add the import directive at the top of both files.
import React from 'react';
Note: It might be useful to run your build with and without the import directive to see how the code changes with each build.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ObiHill |
