jasonkuhrt / graphql-request

Minimal GraphQL client
MIT License
5.74k stars 307 forks source link

Cannot find module` graphql-request` #965

Closed ekasprzyk closed 20 hours ago

ekasprzyk commented 2 days ago

Screenshot

Screenshot 2024-07-03 at 16 02 32

Screenshot 2024-07-03 at 16 04 10

Description

I've been setting jest using SWC in a new sub-repo in a serverless mono-repo we have. We've used it elsewhere and I've mostly copied the deployment from a working one.

The code has been working during deploy and we use serverless-esbuild for the build and deploy to AWS and have no issues. However, when it comes to jest, it's absolutely not happy and fails with the error above.

I have no idea why it's doing that, and I've followed the documentation around module resolution and package type, which everything with similar errors links to. VSCode can see the module fine and is not giving me an error.

Reproduction Steps/Repo Link

-

jonkoops commented 1 day ago

Please provide a minimal and reproducible example that does not include your project code, we cannot fix issues that cannot be reproduced.

slatlasdev commented 21 hours ago

This is due to how Jest imports modules.

By default, Jest is transforming your modules to use require under the hood, even if you use import in your code.

graphql-request does not export a require entry in their package.json, they only support ESM:

{
  "name": "graphql-request",
  "type": "module",
  "exports": {
    ".": {
      "import": {
        "types": "./build/entrypoints/main.d.ts",
        "default": "./build/entrypoints/main.js"
      }
    }
  }
}

I tried adding a "require": "./build/entrypoints/main.js" property next to import, however then we get the error Jest encountered an unexpected token "import".

This is because we are just trying to trick Jest into thinking this module supports CommonJS, but as soon as it hits an ESM import that it doesn't expect inside that file it dies.

To solve this issue, I followed the instructions in https://stackoverflow.com/questions/68956636/how-to-use-esm-tests-with-jest

Specifically adding the following Node option is what allowed me to run Jest tests with ESM:

NODE_OPTIONS=--experimental-vm-modules jest

If graphql-request wanted to fix it from their side they would have to add a require export, but I doubt they would want to do that if they want to go all in on ESM.

jonkoops commented 20 hours ago

Indeed, this sounds like a Jest specific issue. Best option is to try and run Jest in ESM mode. We have no intention of supporting non-standard module systems due to maintenance burden and the compatibility issues that come with shipping modules in a dual format.