Uncaught ReferenceError: process is not defined ReactJS – Code Example

Total
0
Shares

React-Scripts throws the error Uncaught ReferenceError: process is not defined due to it’s dependency on react-error-overlay. The dependencies of react-error-overlay got updated to support webpack V5 which is not compatible with react-scripts V4.

You might get this error in HTMLIFrameElement.

Solutions with Code Examples

1. Upgrade react-scripts

The simplest solution is to upgrade react-scripts to V5. Change react-scripts version in package.json

"dependencies": {    
    "react-scripts": "5.0.0",
}

Then run npm install.

2. Upgrade react-error-overlay to v6.0.9

Delete yarn.lock and package-lock.json files. Then add version for react-error-overlay in package.json

Using Yarn

"resolutions": {
  "react-error-overlay": "6.0.9"
}

Using npm >= v8.3.0

"overrides": {
  "react-error-overlay": "6.0.9"
},

Using npm < v8.3.0

"resolutions": {
    "react-error-overlay": "6.0.9"
},

"scripts":{
    "preinstall": "npx npm-force-resolutions",
},

"devDependencies":{
    "react-error-overlay": "6.0.9",
}

Then run yarn install or npm install accordingly.

3. Using Webpack Plugin

The issue could be solved by using webpack plugin –

plugins:[
  new webpack.DefinePlugin({
      process: {env: {}}
  })
]

If you are using craco then open craco.config.js file and do these updates –

{
  webpack: {
    plugins: {
      add: [
        new webpack.DefinePlugin({
          process: {env: {}}
        })
      ]
    }
  }
}

If you are using customize-cra then open config-overrides.js and do these updates –

const webpack = require('webpack');
const { override, addWebpackPlugin } = require('customize-cra');

module.exports = override(
  addWebpackPlugin(
    new webpack.DefinePlugin({
      process: { env: {} },
    })
  )
);

4. Adding window.process to App.js

Another solution is to add window.process to your App.js file –

useEffect(() => {
    window.process = {
      ...window.process,
    };
  }, []);

5. Using process as dependency in craco

If you are getting this WARNING in DefinePlugin Conflicting values for ‘process.env’, then you need to add process dependency in your craco.config.js.

First install process

Using yarn

yarn add process

Using npm

npm i process

Then add this code to craco.config.js

const webpack = require('webpack');

module.exports = {
webpack: {
     ...
     plugins: {
        add: [
            new webpack.ProvidePlugin({
                process: 'process/browser.js',
            }),
            new webpack.DefinePlugin({
                'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
            }),
        ],
      },
    },
};

Conclusion

In this article we saw various solutions to resolve Uncaught ReferenceError: process is not defined error which is generated in react-scripts. After patching your react project with these mentioned solutions, you will not get this issue.