redux-toolkit
redux-toolkit copied to clipboard
Cannot run codegen CLI command on .cts or .cjs files (CommonJS)
I have a project which uses Vite and thus also uses type:"module" in its package.json.
Error description
When running npx @rtk-query/codegen-openapi I get the following error:
const err = new Error(getErrRequireEsmMessage(filename, parentPath, packageJsonPath))
^
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module:/.../src/api/generationConfig.ts
require() of ES modules is not supported.
require() of /.../src/api/generationConfig.ts from /.../node_modules/@rtk-query/codegen-openapi/lib/bin/cli.js is an ES module file as it is a .ts file whose nearest parent package.json contains "type": "module" which defines all .ts files in that package scope as ES modules.
Instead change the requiring code to use import(), or remove "type": "module" from /.../package.json.
Reason for error
The above error is caused by the config file being inside the package.json project whilst also having type: "module" specified. One fix to get around this is declaring generationConfig.ts as generationConfig.cts instead to tell it to use CommonJS imports instead of ESM.
However, this doesn't work with @rtk-query/codegen-openapi as in the cli file, on line 46, the regex for checking if the path given is to a correct file is as follows
/\.(jsx?|tsx?|jsonc?)?$/
This doesn't match to files ending in .cjs or .cts
Possible solution
An easy fix would be to change the regex to
/\.(c?(jsx?|tsx?)|jsonc?)?$/