dotansimha / graphql-code-generator

A tool for generating code based on a GraphQL schema and GraphQL operations (query/mutation/subscription), with flexible support for custom plugins.
https://the-guild.dev/graphql/codegen/
MIT License
10.78k stars 1.31k forks source link

ViteJS + GraphQL code generator = codegen.ts config bug #8509

Closed forestjava closed 1 year ago

forestjava commented 1 year ago

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

2) install yours

npm install graphql
npm install -D @graphql-codegen/cli

3) initialize Application built with React

npx graphql-code-generator init
npm install

4) 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

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

gterras commented 1 year ago

Same issue from a fresh sveltekit install :

error TS5095: Option 'preserveValueImports' can only be used when 'module' is set to 'es2015' or later.

but sveltekit has

        "moduleResolution": "node",
        "module": "esnext",
        "target": "esnext"

If preserveValueImports is set to false :

   TypeScriptLoader failed to compile TypeScript:  require() of ES modules is not supported.  

Followed https://www.the-guild.dev/graphql/codegen/docs/getting-started/esm-typescript-usage with no luck.

gterras commented 1 year ago

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

ardatan commented 1 year ago

The issue provides a minimal reproduction available on GitHub, Stackblitz or CodeSandbox.

Please provide your reproduction on these platforms not as zip files.

stroncod commented 1 year ago

I'm having the same issue on VitaJS and Typescript setup. I'm following the Apollo tutorial and throws me the exact error. To duplicate:

  1. $ yarn create vite test-weird-error --template react-ts
  2. $ yarn add -D typescript graphql @graphql-codegen/cli @graphql-codegen/client-preset
  3. $ graphql-codegen

There is some known work around? Thanks!

matthewaptaylor commented 1 year ago

I'm having the same issue on VitaJS and Typescript setup. I'm following the Apollo tutorial and throws me the exact error. To duplicate:

  1. $ yarn create vite test-weird-error --template react-ts
  2. $ yarn add -D typescript graphql @graphql-codegen/cli @graphql-codegen/client-preset
  3. $ graphql-codegen

There is some known work around? Thanks!

Try converting your codegen.ts config into yaml

stroncod commented 1 year ago

It worked. Remember to run npm install or yarn install after. Thanks!

wesharper commented 1 year ago

In my case, changing to .yaml isn't an effective solution. I'd like to use environment variables in my config to determine which schema endpoint to use. Any other options?

FYI, this is happening in a pretty new Astro project as well.

patsissons commented 1 year ago

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",
}
SiNONiMiTY commented 1 year ago

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",
}

This conversion will do until the ESM loader works correctly :)

n1ru4l commented 1 year ago

Related to https://github.com/dotansimha/graphql-code-generator/issues/8862

n1ru4l commented 1 year ago

The issue here is that cosmiconfig does not properly handle ESM/MTS https://github.com/davidtheclark/cosmiconfig/issues/224

If anyone wants to help resolving this issue in the upstream dependency that would be great!

n1ru4l commented 1 year ago

There is a reproduction here: https://github.com/dotansimha/graphql-code-generator/pull/8988

lloydjatkinson commented 1 year ago

package.json: "type": "module",

codegen.cjs:

import { CodegenConfig } from '@graphql-codegen/cli';
/** @type {import('@graphql-codegen/cli').CodegenConfig} */
const config = {
    schema: 'https://swapi-graphql.netlify.app/.netlify/functions/index',
    documents: ['src/**/*.tsx'],
    ignoreNoDocuments: true, // for better experience with the watcher
    generates: {
        './src/gql/': {
            preset: 'client'
        },
    },
};

export default config;

vite.config.ts:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
})

tsconfig.json:

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

Both tsconfig and vite config are the default as Vite creates them.

"codegen": "graphql-codegen --config codegen.cjs": Cannot use import statement outside a module

Changing the file extension does not fix the issue.

n1ru4l commented 1 year ago

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

soumi-akira commented 1 year ago

Same issue here.

error TS5095: Option 'preserveValueImports' can only be used when 'module' is set to 'es2015' or later.

It seems "extends": "@vue/tsconfig/tsconfig.web.json" in tsconfig.json cause this problem. When I remove (or rename) this, it works fine.

jbaubree commented 1 year ago

If it can help, this is my working solution:

// package.json
{
  ...
  "scripts": {
    ...
    "codegen": "graphql-codegen --config codegen.yml",
  },
  "devDependencies": {
    ...
    "ts-node": "x.x.x",
  },
  ...
}
// tsconfig.json
{
  ...
  "ts-node": {
    "compilerOptions": {
      "module": "CommonJS"
    }
  }
}
// codegen.yml
...
require:
  - ts-node/register