esm: add pjson.importInterop to support __esModule #40902
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.
This is another attempt at solving #40891 following the discussion starting with #40892 (comment). The previous attempt is #40892 and I made a different PR because they're different solutions and have pros and cons.
This PR adds an option "importInterop" to package.json. When enabled,
import
statements in that package will behave slightly different with respect to default exports if the imported module is CJS.module.exports.__esModule
as a truthy value, the value ofmodule.exports.default
is used as the default export.module.exports
is used as the default export. (existing behavior)It allows better interoperation between full ES modules and CJS modules
transformed from ES modules by Babel or tsc. Consider the following
example:
When imported from the following module:
with the following package.json:
Then it will print "Hello".
Fixes: #40891
Unlike the previous approach, it doesn't (and doesn't intend to) change the default behavior. It still solves the problem illustrated in #40891 because only ESM → CJS boundaries are problematic and such boundaries will most likely emerge when the importing package is migrating from CJS to ESM. Even if the imported package is inactive, it is easy to configure the importing package as it is the package that is migrating to ESM.
I used
getPackageScopeConfig
to retrievepackage.json
. I think it is a reliable one because it is already used in#path/to/alias
imports. I'm unsure about its performance implication, but the effect is limited to ESM → CJS edges.