ESM Support
The generated code should work with projects using ESM and modern versions of nodejs.
It will try to detect this from the package.json file, based on whether the type field is set to module.
You can override this by passing the --ts-is-esm-project <bool> flag to the code generator,
or using the OPENAPI_TS_IS_ESM_PROJECT environment variable.
Project Configuration
package.json
Ensure that you have "type": "module" in your package.json file.
{
"type": "module"
}tsconfig.json
Ensure that you have "module": "nodenext" in your tsconfig.json file,
and have rewriteRelativeImportExtensions set to true.
{
"compilerOptions": {
"module": "nodenext",
"target": "esnext",
// make typescript replace .ts file extensions in imports with .js in transpiled code
"rewriteRelativeImportExtensions": true,
// optional
"verbatimModuleSyntax": true,
}
}How does it work?
The code generator CLI itself, and the runtime packages still ship as CommonJS modules. However, NodeJS supports loading CommonJS from either ESM or CommonJS contexts (ref: interoperability-with-commonjs )
This means you can run the generator, and import the runtime code from both ESM and CommonJS projects.
We do have to change one thing in the generated code, for it to work with ESM, and that’s including file extensions in imports.
Eg:
import {
// schema names
} from "./schemas"Becomes
import {
// schema names
} from "./schemas.ts"This is controlled by the --ts-is-esm-project true flag mentioned above, though in most cases it should be detected automatically.