When using esbuild with external react I get Dynamic require of "react" is not supported

Viewed 3786

I am trying to use esbuild with external react.

here is my esbuild command in my package.json file

  "scripts": {
    "esbuild": "esbuild ./src/index.js --bundle --outfile=dist/esmain.js --loader:.js=jsx --external:react-dom --external:react "
  }

when running the command, I get no errors:

npm run esbuild

> @1.0.0 esbuild C:\prog
> esbuild ./src/index.js --bundle --outfile=dist/esmain.js --loader:.js=jsx --external:react-dom --external:react


  dist\esmain.js  32.7kb

Done in 13ms

The problem is that when I run the program in the browser (chrome), I get this error in the console

Uncaught Error: Dynamic require of "react" is not supported
    at __require (esmain.js:12)
    at esmain.js:27
    at esmain.js:899

Any ideas how to fix this?

3 Answers

What i think from the error is.There is somewhere in the code you have imported react like this which is actually a commonjs convention mostly used in Nodejs but not supported by Browsers

const react = require('react');

So just do a code search within your code editor against require('react') and replace it with the import statement. Hope it will work for you

If what you were tryinig to do was to access react and react-dom from global window scope like window.React and window.ReactDOM, then this is NOT what esbuil external option does.

According to documentation:

Instead of being bundled, the import will be preserved (using require for the iife and cjs formats and using import for the esm format) and will be evaluated at run time instead.

On top of that, I assume, esbuild adds some check whether the require is supported in the target environment, which in the browser it is not by default. Hence the error.

You would need the esbuild-plugin-external-global and configure the plugin as such:

esbuild.build({
  ...
  plugins: [
    externalGlobalPlugin({
      'react': 'window.React',
      'react-dom': 'window.ReactDOM',
    })
  ]
  ...
});

At this point you might need a build script instead of callin esbuild with options via command line.

What are you trying to achieve by marking react as external? Based on what I read in the doc, the only use-case I can think of is a website that has the react common js loaded & you want to reuse this code in your script. But then my question was - why have 2 apps on the same page, and on top of that build differently.

No idea if this will help, but I wrote an article about building create-react-app generated with esbuild - building react code seemed to go pretty smooth, especially comparing to some other frameworks.

Related