[internal] Use the Node.js behavior for default imports#12795
[internal] Use the Node.js behavior for default imports#12795nicolo-ribaudo merged 3 commits intobabel:mainfrom
Conversation
|
Build successful! You can test your changes in the REPL here: https://babeljs.io/repl/build/43365/ |
|
This pull request is automatically built and testable in CodeSandbox. To see build info of the built libraries, click here or the icon next to each commit SHA. Latest deployment of this branch, based on commit a9e4366:
|
babel.config.js
Outdated
| } | ||
|
|
||
| // Match the Node.js behavior (the default import is module.exports) | ||
| function pluginDefaultImportNode({ types: t }) { |
There was a problem hiding this comment.
This plugin transforms import foo from "mod" into const foo = require("mod"), which is what Node.js does.
82a529a to
7b46d50
Compare
ccb874b to
439c25e
Compare
8d8fd33 to
a9e4366
Compare
|
|
||
| convertESM ? "@babel/proposal-export-namespace-from" : null, | ||
| convertESM ? "@babel/transform-modules-commonjs" : null, | ||
| convertESM ? pluginNodeImportInterop : null, |
There was a problem hiding this comment.
Q: This plugin will be no-op for babel parser and some plugins bundled by Rollup, is that intended?
There was a problem hiding this comment.
It is not a problem because all the bundled packages don't have any third-party dependency. And even if they did, it would only be a problem if these third-party dependencies used __esModule.
However, I asked to reopen rollup/plugins#635 to add an option to @rollup/plugin-commonjs to mirror the Node.js behavior.
|
I'm merging this PR with a single review since it's just internal bookkeeping and doesn't affect in any way our users. I will soon open a follow-up for |
This is another step for #11701.
Node.s doesn't check if
__esModuleis defined when importing a CJS module from ESM, and thedefaultimport is always mapped tomodule.exports. This is different from how Babel handles the interop, and this PR aligns the compilation behavior to Node.js to make it easier to migrate to native ESM.We might also consider adding this as an option to
transform-modules-commonjs, but for now I just added a small internal plugin (not 100% compliant, because it doesn't hoist compiled imports) to our config.When this is merged, I will open a new PR to avoid using
__dirname/__filename/requirein our sources so that we'll only be using Node.js-compliant modules.