ardatan / graphql-tools

:wrench: Utility library for GraphQL to build, stitch and mock GraphQL schemas in the SDL-first approach
https://www.graphql-tools.com
MIT License
5.35k stars 816 forks source link

Error using custom loaders after migrating my project to ESM #6656

Open eirikur-nc opened 1 week ago

eirikur-nc commented 1 week ago

Issue workflow progress

Progress of the issue based on the Contributor Workflow


Describe the bug

graphql-codegen fails after having added "type": "module" to all packages in a monorepo

To Reproduce:

https://codesandbox.io/p/devbox/q5w2zq

Expected behavior

Being able to author custom data loaders in ESM format

Environment:

Additional context

I'm working in a monorepo that uses graphql-codegen to generate type information from our GraphQL schema (which has served us well, thanks!) Due to issues with having a mixture of CommonJS and ESM packages in the repo, we decided to switch entirely over to ESM. We added "type": "module" to all our package.json files. We modified our scripts to run graphql-codegen-esm We have a config file in yml format that specifies custom loaders for two schemas. Example

schema:
  - '${PWD}/src/graphql/types.graphql'
  - ${PWD}/../graphqlSchema.json:
        loader: '${ROOT_PATH}/configs/codegen/fileLoader.js'
  - http://127.0.0.1:5000/api/graphql:
      loader: '${ROOT_PATH}/configs/codegen/urlLoader.js'

Those failed to load properly. I converted them from CommonJS to ESM format and changed their file extensions to *.mjs but that did not suffice.

I found this SO question which got me on the right track https://stackoverflow.com/questions/75253732/codegen-config-cant-load-custom-schema-loader

In packages/load/src/utils/custom-loader.ts there's a function named getCustomLoaderByPath which uses createRequire which cannot be used to load ES modules. I've managed to work around this issue by patching the package to use a dynamic import instead. The purpose of this issue is to get that change applied upstream to the benefit of others. I will follow up with a PR.

ardatan commented 1 week ago

Thanks for creating the issue. Could you please create a reproduction on CodeSandbox so we can also debug and help you better with it?

eirikur-nc commented 1 week ago

Thanks for creating the issue. Could you please create a reproduction on CodeSandbox so we can also debug and help you better with it?

Sure: https://codesandbox.io/p/devbox/q5w2zq I've updated the description with a link

eirikur-nc commented 6 days ago

A PR with a fix is ready for review #6660