graphql-tools
graphql-tools copied to clipboard
Error using custom loaders after migrating my project to ESM
Issue workflow progress
Progress of the issue based on the Contributor Workflow
- [x] 1. The issue provides a reproduction available on Github, Stackblitz or CodeSandbox
Make sure to fork this template and run
yarn generatein the terminal.Please make sure the GraphQL Tools package versions under
package.jsonmatches yours. - [x] 2. A failing test has been provided
- [ ] 3. A local solution has been provided
- [x] 4. A pull request is pending review
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:
- OS: macOs 15.0.1
@graphql-tools/load: 8.0.0- NodeJS: 18.18.0
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.