javascriptreactjsreact-hooksesbuild

React crash on render bundled component


I got the error Invalid hook call when try to render bundled component in another react app. enter image description here

My component build script is look like this:

 "build": "esbuild ./src/index.js --external:'react' --bundle --format=cjs --loader:.js=jsx --outdir=dist",

and the component has peer dependency of react:

  "peerDependencies": {
    "react": "^16.8.0 || ^17.0.0 || ^18.0.0",
    "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0"
  },

when I bundle it and then pack it or copy the bundle to another react project it's throw this error.

I run the

npm list

and didnt find any extra version of react

enter image description here

I know the component code is fine because when I run directly the component using story-book it's render just fine.

I tried to use single peerDependency version of react and I checked all the versions


Solution

  • Solved it! There was a syntax error in the esbuild command:

    "build": "esbuild ./src/index.js \"--define:process.env.NODE_ENV='production'\" --external:react --bundle --format=cjs --loader:.js=jsx --outdir=dist && cp -f ./dist/index.js ./example/index.js",
    

    Excluding react from the bundle probably didn't work, after removing the quotation mark it works fine.