vite
vite copied to clipboard
fix(resolve): prioritize `main` field over `mainFields` for `require`s
Description
When a require
is performed the modules resolution currently prioritizes the mainFields
option over the fact that a require
has been used, this (especially given the default mainFields
value) can lead to require
s being resolved to browser entries instead of a potential cjs module
entry. This PR addresses this by priotizing a potential main
field over the mainField
.
Details on how we encountered this issue
This was encountered as an issue when trying to run Remix code inside the workerd
runtime via the environments API, there we encountered situations in which some modules imported via require
would require
packages but would receive esm entries instead of cjs ones, causing the following issue:
TypeError: Cannot use require() to import an ES Module.
This happened when
react-router-dom
(package.json) was being require
d from @remix-run/react
(code)
by adding some ad-hoc hacks to make the above work this issue would show up again
for react-router
(packae.json) require
d from react-router-dom
itself (code)
by also hacking the above we'd re-encounter the issue with:
@remix-run/router
(package.json) being require
d from react-router
(code)
and so on...