cloudflare / workers-sdk

⛅️ Home to Wrangler, the CLI for Cloudflare Workers®
https://developers.cloudflare.com/workers/
Apache License 2.0
2.63k stars 692 forks source link

🐛 BUG: import issue of packages with `workerd` runtime key[vitest-pool-workers] #6465

Open m-shaka opened 2 months ago

m-shaka commented 2 months ago

Which Cloudflare product(s) does this pertain to?

Workers Vitest Integration

What version(s) of the tool(s) are you using?

0.4.21

What version of Node are you using?

20.11.0

What operating system and version are you using?

Mac Sonoma 14.1.2

Describe the Bug

Observed behavior

Importing packages with workerd runtime key from globalSetup fails.

I tried to use Postgres.js from a globalSetup file to run database migration, but this error was raised.

Error: Only URLs with a scheme in: file, data, and node are supported by the default ESM loader. Received protocol 'cloudflare:'

This is because

As proof of that, if you add this setting to your vitest config, globalSetup works

    ssr: {
        resolve: {
            conditions: ['import']
        }
    }

However, then, tests using Postgres.js fail

 FAIL  test/index.spec.ts [ test/index.spec.ts ]
Error: No such module "Users/xxx/repro-vitest-pool-workers-import-error/node_modules/.pnpm/postgres@3.4.4/node_modules/postgres/src/os".
  imported from "Users/xxx/repro-vitest-pool-workers-import-error/node_modules/.pnpm/postgres@3.4.4/node_modules/postgres/src/index.js"

I guess this is because resolve condition is no longer workerd. Vitest is trying to import files for runtime other than workerd.

Expected behavior

You can import postgres correctly

Steps to reproduce

Please provide the following:

Please provide a link to a minimal reproduction

https://github.com/m-shaka/repro-vitest-pool-workers-import-issue

Please provide any relevant error logs

No response

m-shaka commented 2 weeks ago

Environment API of Vite may help us https://main.vitejs.dev/guide/api-environment