fix: set require.main when importing CJS from ESM #11790
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
For ESM tests,
jestAdapter()callsRuntime.unstable_importModule()->Runtime.loadEsmModule():https://github.com/facebook/jest/blob/d38156ccd7a68e52372b4eb6fc02afbadd5b703e/packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts#L74-L78
It doesn't call
Runtime.requireModule()->Runtime._loadModule()->Runtime._execModule(), so it doesn't setRuntime._mainModule/require.main:https://github.com/facebook/jest/blob/d38156ccd7a68e52372b4eb6fc02afbadd5b703e/packages/jest-runtime/src/index.ts#L1205-L1207
Consequently
require.mainisnull:I haven't investigated whether this changed in #10621 (whether previously
require.mainwas alwaysundefined, or only when usingisolateModules(), ∴ regression?). Either way, this PR proposes to copythis._mainModule = moduleto the ESM code path.I'm not sure where is the "right" location -- between
loadEsmModule()andlinkAndEvaluateModule()seemed analogous to the existing location inRuntime._execModule()?