vitest-dev / vitest

Next generation testing framework powered by Vite.
https://vitest.dev
MIT License
13.17k stars 1.19k forks source link

Dynamic import error doesn't have error code `ERR_MODULE_NOT_FOUND` #6699

Open hi-ogawa opened 1 month ago

hi-ogawa commented 1 month ago

Describe the bug

For this code:

try {
  await import('no-such-package');
} catch (e) {
  console.log('code:', e.code);
  console.log('message:', e.message);
}

On Node

❯ node src/repro.js
code: ERR_MODULE_NOT_FOUND
message: Cannot find package 'no-such-package' imported from /home/projects/vitest-dev-vitest-53av14/src/repro.js

On Vitest

❯ vitest

stdout | src/repro.test.js > repro
code: undefined
message: Failed to load url no-such-package (resolved id: no-such-package) in /home/projects/vitest-dev-vitest-53av14/src/repro.test.js. Does the file exist?

It looks like this was brought up previously in https://github.com/vitest-dev/vitest/issues/326. It doesn't throw during import analysis anymore, but dynamic import error still doesn't have ERR_MODULE_NOT_FOUND code (or maybe it did when it's fixed but regression).

There are some places injecting ERR_MODULE_NOT_FOUND, so maybe it works in some cases, but not the basic case above. https://github.com/vitest-dev/vitest/blob/5e6de2742f329b7e65fe3dff4827b5134d777009/packages/vite-node/src/client.ts#L296-L296

Vite SSR injects ERR_MODULE_NOT_FOUND https://github.com/vitest-dev/vite/blob/95020ab49e12d143262859e095025cf02423c1d9/packages/vite/src/node/ssr/fetchModule.ts#L78, so it's working there as well.

Reproduction

https://stackblitz.com/edit/vitest-dev-vitest-53av14?file=src%2Frepro.test.js

System Info

(stackblitz)

  System:
    OS: Linux 5.0 undefined
    CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 0 Bytes / 0 Bytes
    Shell: 1.0 - /bin/jsh
  Binaries:
    Node: 18.20.3 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 10.2.3 - /usr/local/bin/npm
    pnpm: 8.15.6 - /usr/local/bin/pnpm
  npmPackages:
    @vitest/ui: latest => 2.1.2 
    vite: latest => 5.4.8 
    vitest: latest => 2.1.2

Used Package Manager

npm

Validations

sheremet-va commented 1 month ago

Vite SSR injects ERR_MODULE_NOT_FOUND vitest-dev/vite@95020ab/packages/vite/src/node/ssr/fetchModule.ts#L78, so it's working there as well.

It only injects modules for externalized dependencies as far as I remember.

I think it might be a good idea to inject the code, but then the message should also be changed to the same one Node.js throws.