graphql-code-generator: ViteJS + GraphQL code generator = codegen.ts config bug

Describe the bug

TypeScriptLoader failed to compile the Codegen Config File codegen.ts Please find codegen.ts, tsconfig.json and the entire my-app.zip attached.

codegen.ts.zip

tsconfig.json.zip

my-app.zip

Your Example Website or App

npm run codegen

Steps to Reproduce the Bug or Issue

  1. create React Typescript application via
npm create vite@latest my-app
cd my-app
npm install
  1. install yours
npm install graphql
npm install -D @graphql-codegen/cli
  1. initialize Application built with React
npx graphql-code-generator init
npm install
  1. try to call codegen
npm run codegen

Expected behavior

As a user I expected code generation, but getting the error:

TypeScriptLoader failed to compile TypeScript:
Must use import to load ES Module: \my-app\codegen.ts
require() of ES modules is not supported.
require() of \my-app\codegen.ts from \my-app\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 \my-app\package.json.

Screenshots or Videos

No response

Platform

  • OS: Windows 10
  • NodeJS: 16.17.1
  • graphql version: ^16.6.0
  • @graphql-codegen/* version: 2.13.7
  • @graphql-codegen/client-preset version: 1.0.7

Codegen Config File


import type { CodegenConfig } from '@graphql-codegen/cli';

const config: CodegenConfig = {
  overwrite: true,
  schema: "http://localhost:4000",
  documents: "src/**/*.tsx",
  generates: {
    "src/gql": {
      preset: "client",
      plugins: []
    }
  }
};

export default config;

Additional context

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 9
  • Comments: 16

Most upvoted comments

for those running into this issue where a static YAML file is not a solution, you can rename your file to codegen.cjs

/** @type {import('@graphql-codegen/cli').CodegenConfig} */
const config = {
  // ...
}

module.exports = config

and then modify your scripts in package.json accordingly

"scripts": {
  "codegen": "graphql-codegen --config codegen.cjs",
}

@lloydjatkinson You cannot use import in a commonjs module. Remove the import { CodegenConfig } from '@graphql-codegen/cli'; part.

FYI I solved this by turning codegen.ts to codegen.yaml as suggested here https://github.com/dotansimha/graphql-code-generator-community/issues/225