reduxjs/redux-toolkit

codegen-openapi: ERR_REQUIRE_ESM possible fix

ignassew opened this issue · 0 comments

Hello,
I just spent 2 hours on figuring this out so I might as well share a solution.

I was getting this error:

Error [ERR_REQUIRE_ESM]: require() of ES Module /home/ignacy/Projects/redacted/frontend/openapi-config.js from /home/ignacy/Projects/redacted/frontend/node_modules/.pnpm/@rtk-query+codegen-openapi@1.2.0_openapi-types@12.1.3/node_modules/@rtk-query/codegen-openapi/lib/bin/cli.js not supported.
openapi-config.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.
Instead either rename openapi-config.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in /home/ignacy/Projects/redacted/frontend/package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).

    at run (/home/ignacy/Projects/redacted/frontend/node_modules/.pnpm/@rtk-query+codegen-openapi@1.2.0_openapi-types@12.1.3/node_modules/@rtk-query/codegen-openapi/lib/bin/cli.js:50:28)
    at Object.<anonymous> (/home/ignacy/Projects/redacted/frontend/node_modules/.pnpm/@rtk-query+codegen-openapi@1.2.0_openapi-types@12.1.3/node_modules/@rtk-query/codegen-openapi/lib/bin/cli.js:45:5) {
  code: 'ERR_REQUIRE_ESM'
}

Possible fixes like creating an empty .prettierrc (see #4038) or downgrading prettier (see #3604) didn't work for me.

Then I read the docs again, and found out that .json config is supported.
I converted my openapi-config.js to json and everything worked correctly.

I don't know what's the core problem causing this issue, nor I have the time to investigate.
I'm only sharing this to help others struggling with the same problem.

Cheers