Skip to content

Using codegen.ts in an ESM project causes cosmiconfig-typescript-loader to throw an "ES modules is not supported" error #225

Open
@tars0x9752

Description

@tars0x9752

Describe the bug

I don't know if it's a bug or not, but I'm reporting it just in case. See steps to reproduce below for a more detailed bug/issue explanation.

In short, if you set "type": "module" in package.json and use codegen.ts as a config file, graphql-codegen fails because of ESM error by cosmiconfig-typescript-loader.

If you use codegen.yml or delete "type": "module" from package.json, the error will not occur.

Your Example Website or App

Not yet.

Steps to Reproduce the Bug or Issue

  1. Add "type": "module" in package.json
  2. Run npx graphql-code-generator init and leave everything as default to create codegen.ts
  3. Run generated codegen npm script graphql-codegen --config codegen.ts. It throws the following error:
TypeScriptLoader failed to compile TypeScript:
Must use import to load ES Module: /path/to/project/codegen.ts
require() of ES modules is not supported.
require() of /path/to/project/codegen.ts from /path/to/project/node_modules/cosmiconfig-typescript-loader/dist/cjs/index.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 /path/to/project/package.json.

It maybe a bug in cosmiconfig-typescript-loader.

Expected behavior

Code generation completes without throwing an error.

Screenshots or Videos

No response

Platform

  • OS: Linux x86_64
  • NodeJS: 18.8.0
  • "typescript": "4.8.4"
  • "graphql": "16.6.0"
  • "@graphql-codegen/cli": "2.13.7"
  • "@graphql-codegen/typescript": "2.7.4"
  • "@graphql-codegen/typescript-resolvers": "2.7.4"

Codegen Config File

No response

Additional context

a sample tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist",
    "target": "es2021",
    "lib": ["es2021"],
    "module": "Node16",
    "moduleResolution": "Node16",
    "esModuleInterop": true
  },
  "include": ["src"]
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions