vite icon indicating copy to clipboard operation
vite copied to clipboard

fix(resolve): prioritize `main` field over `mainFields` for `require`s

Open dario-piotrowicz opened this issue 1 month ago • 6 comments

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 requires 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 required 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) required from react-router-dom itself (code)

by also hacking the above we'd re-encounter the issue with: @remix-run/router (package.json) being required from react-router (code)

and so on...

dario-piotrowicz avatar May 28 '24 11:05 dario-piotrowicz