Fixing duplicate import of preact with react-router — Cannot read properties of undefined (reading '__H') #6528
itsgiacoliketaco
started this conversation in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
If you're using preact with react-router and running tests with Vitest, you may experience the following error when running tests:
The error comes from somewhere in the
preact/hooks
package.The error arises because both the CJS and ESM versions of the
preact
andpreact/hooks
packages are being loaded (more info here). In my case, my code is ESM (type: module
), so it loads the ESM version of preact. But Vite loads the CJS version of react-router, which tries torequire
(notimport
) React, which loads the CJS version of preact. This happens despite explicitly aliasing "react" to the CJS (or ESM) version of preact—I think because Vitest does not aliasrequire
, onlyimport
. I think this also explains why this setup works in Vite (dev server + production build) with no issues, but not in Vitest.This is an example of the dual-package hazard.
The solution: add
resolve.mainFields = ["module"]
to your Vite config. Here's a snippet that does this only when running in test mode.This appears to force Vitest to load the ESM version of react-router, which then imports preact correctly. Something in react-router's package.json prevents Vite/Vitest from doing this by default.
Full credit to @hi-ogawa for this solution! It took me a while to stumble across that issue, so I'm writing this discussion post hoping it will include the right keywords, and people searching will be directed here immediately. Then perhaps the many hours it took me to resolve this will have been worth it 😝
Related issues to try other possible solutions:
P.S. Still super grateful for Vite + Vitest!
Beta Was this translation helpful? Give feedback.
All reactions