Search code examples
node.jsreactjsnpmes6-modules

react app build fails with 'ERR_REQUIRE_ESM'


When I am trying to run the build command for my react application I am seeing this error failing the build:


var stripAnsi = require('strip-ansi');
                ^

Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\rahul\Documents\project_name\node_modules\strip-ansi\index.js from C:\Users\rahul\Documents\cambian\cambian-widget-client\node_modules\react-dev-utils\FileSizeReporter.js not supported.
Instead change the require of index.js in C:\Users\rahul\Documents\project_name\node_modules\react-dev-utils\FileSizeReporter.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (C:\Users\rahul\Documents\project_name\node_modules\react-dev-utils\FileSizeReporter.js:15:17)
    at Object.<anonymous> (C:\Users\rahul\Documents\project_name\node_modules\react-scripts\scripts\build.js:35:26) {
  code: 'ERR_REQUIRE_ESM'
}
error Command failed with exit code 1.

But when I delete the lockfile and re-run the build command, it executes successfully. Then again the new builds fails until the lockfile is removed.

This is causing a major issue as we have to manually deploy the application every time a change has been done.

This has been working fine two weeks ago and I can confirm neither new packages have been added nor any package has been updated

What I have tried?

  • upgrading node, npm, yarn but nothing worked
  • yarn cache clean
  • yarn audit fix --force

Build command used: react-scripts build

Enviroment:

node: 16.19.0
npm: 9.8.1
yarn: 1.22.19

React packages version

    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "^5.0.0",

Solution

  • The only way I have found around this is a resolution in package.json forcing strip-ansi down to 6.0.0 or 6.0.1. It became pure ESM in 7.0.0. Something like this:

    {
      ...
      "resolutions": {
        "strip-ansi": "6.0.0"
      }
    }
    

    If you use npm rather than yarn (which I see the OP isn't, but for others), then use an override:

    {
      ...
      "overrides": {
        "strip-ansi": "6.0.0"
      }
    }