Open Janpot opened 1 month ago
Vitest's browser mocking relies msw
, which has a dependency path-to-regexp@6
. It looks like user code's path-to-regexp@8
mixes up dependency versions due to Vite cjs dependency optimization.
I am encountering same issue when using vitetest browser mode.
Failed to fetch dynamically imported module: http://localhost:5173/@fs/C:/Users/web-client/virtual:wxt-setup?import&v=1727619790892
In my case I could not use any environment such jsdom due to poor support of selectors in querySelector API. Error:
// jsdom
SyntaxError: unknown pseudo-class selector ':not([type]'
//happy-dom
DOMException: Failed to execute 'matches' on 'HTMLButtonElement': 'button:not' is not a valid selector.
This code has no errors when I run in browser.
@hi-ogawa, does that happen because MSW is not treated as ESM by Vite? Otherwise, why would Vite attempt to optimize CJS dependency?
does that happen because MSW is not treated as ESM by Vite? Otherwise, why would Vite attempt to optimize CJS dependency?
The issue might be a bit more complicated.
Vitest configures optimizeDeps.exclude
so that msw (and its dependencies including path-to-regexp@6
) won't be optimized and thus they are served to browser directly as ESM https://github.com/vitest-dev/vitest/blob/5e6de2742f329b7e65fe3dff4827b5134d777009/packages/browser/src/node/plugin.ts#L204-L205
However, when users have its own path-to-regexp@8
in their Vite app (or Vitest browser test), Vite currently picks up the one from the user, which is considered a bug on Vite https://github.com/vitejs/vite/issues/9948
I thought users can explicitly do optimizeDeps.exclude: ["path-to-regexp"]
as a workaround, but it looks like the latest path-to-regexp@8
dropped "esm-ish" export "module": "dist.es2015/index.js"
, which was available on path-to-regexp@6
, so Vite have no choice but to optimize cjs-only path-to-regexp@8
, which is then deduping path-to-regexp@6
inside msw
.
This was my observation so far and unfortunately I haven't found a way to make this setup work (or even workaround) yet.
Describe the bug
Testing a component that imports latest
path-to-regexp
, and that also mocks some modules.This results in error:
Looking at the devtools, it seems like mock service worker is using an unintended version of
path-to-regexp
:Reproduction
pnpm install
pnpm test
System Info
Used Package Manager
pnpm
Validations