New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Enhancement: Improve CJS → ESM support #14998
Enhancement: Improve CJS → ESM support #14998
Conversation
|
For maintainers only:
|
This comment has been minimized.
This comment has been minimized.
@sokra requested/suggested |
fix externals add test case
Ohhh, now I see what you meant. Thanks! I just ran it locally with the |
Thanks |
I've created an issue to document this in webpack/webpack.js.org. |
@@ -550,6 +550,7 @@ class ExternalModule extends Module { | |||
case "commonjs": | |||
case "commonjs2": | |||
case "commonjs-module": | |||
case "commonjs-static": | |||
return getSourceForCommonJsExternal(request); | |||
case "node-commonjs": |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In order for Node.js to detect named exports in CJS, they must be statically available. However, without this change, webpack does not produce exports that way—webpack will respect source code that is originally written in such a way, but it won't itself produce it (ex if the source code is ESM).
The outputted code will now look like:
And when imported into an ESM file:
What kind of change does this PR introduce?
Enhancement
Did you add tests for your changes?
Will do once approach etc are confirmed.
Does this PR introduce a breaking change?
No: It requires the user to opt-in via configuration flag. Also, Node.js still automatically adds the named exports to
default
anyway (in addition to exposing them as named exports).What needs to be documented once your changes are merged?
New
output.library.type
optioncommonjs-static
which is similar tocommonjs-module
but emits code in a statically analyse-able way, so Node.js is able to construct named exports in it's commonjs esm compat layer.Exports must be statically known to webpack for this to work.
optimization.providedExports
must not be disabled.