Skip to content

fix(ssr): avoid resolving ESM for CJS dependencies#5693

Merged
patak-cat merged 2 commits intovitejs:mainfrom
aleclarson:fix/ssr-cjs
Nov 16, 2021
Merged

fix(ssr): avoid resolving ESM for CJS dependencies#5693
patak-cat merged 2 commits intovitejs:mainfrom
aleclarson:fix/ssr-cjs

Conversation

@aleclarson
Copy link
Copy Markdown
Contributor

Description

This PR is related to module resolution in externalized dependencies only.

CJS modules use require, which doesn't support ESM modules, so we can't use the same InternalResolveOptions that are used for import statements within modules transpiled by Vite (aka non-externalized modules).

I've added a tryEsmOnly option to InternalResolveOptions. If this option is true and CJS resolution fails, tryNodeResolve will try ESM resolution options (eg: pkg.module field and import condition in pkg.exports). With this option, CJS resolution is preferred.

Then, we only set tryEsmOnly: true for non-externalized modules, thus ensuring that the hookNodeResolve callback never uses ESM resolution for a CJS importer.

TODO: We might also need to add a preferEsm option to InternalResolveOptions, so Vite projects with type: module in their package.json can avoid Node's CJS compat mode.

Fixes #5673


What is the purpose of this pull request?

  • Bug fix
  • New Feature
  • Documentation update
  • Other

@aleclarson aleclarson added feat: ssr p5-urgent Fix build-breaking bugs affecting most users, should be released ASAP (priority) labels Nov 15, 2021
Copy link
Copy Markdown
Contributor

@frandiox frandiox left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Looks like this fixes issues with 2.7.0-beta.0 we had in Hydrogen 🎉

@patak-cat patak-cat merged commit b937ea4 into vitejs:main Nov 16, 2021
@aleclarson aleclarson deleted the fix/ssr-cjs branch February 25, 2022 20:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feat: ssr p5-urgent Fix build-breaking bugs affecting most users, should be released ASAP (priority)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SSR: issues with the Vega package ecosystem - not resolving ESM imports in a .js file, require is not defined

3 participants