Search code examples
reactjsesbuild

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

  • It looks like there is a statement in the esbuild docs: (bottom of the linked block)

    esbuild app.js --bundle --loader:.js=jsx

    the --loader:.js=jsx statement will use the jsx loader on js files


    So your script may look something like:

    "build": "esbuild src/App.js --bundle --minify --sourcemap --outfile=public/bundle.js --loader:.js=jsx",
    

    The docs state you can also do this within a config script and not the CLI:

    require('esbuild').buildSync({
      entryPoints: ['app.js'],
      bundle: true,
      loader: { '.js': 'jsx' },
      outfile: 'out.js',
    })