ES Module externals are treated as CommonJS modules by webpack
See original GitHub issueWebpack treats all modules as CommonJS by default, and only treats them as ESM when they have the __esModule
property defined on them (link to webpack code). This is a problem when using external native ES modules, since native ES modules intentionally do not have the __esModule
property defined on them. I believe that webpack 5 will solve this problem when they implement ESM externals, but the last time I checked that was not yet implemented.
The effect of treating the module as CommonJS is that the difference between default / named exports is not captured, so you have to change the way you import the library to be incorrect in order for it to work with webpack.
The obvious solution to this problem would be to add __esModule
properties to all the imported externals. However, ES Module objects are not extensible, so that option is not possible. So as a workaround I created this package which will deep clone the module and add the __esModule
property. I also created this branch on my fork of esm-webpack-plugin that inlines that code into the plugin, and have confirmed that it solves the problem. Here’s the diff of what I changed.
Admittedly, having to inline that much code into the bundle is not ideal, and one could argue that the implementation approach is a bit of a workaround. However, it works well in my testing so far. Could you comment @purtuga, on what you think would be a good implementation approach for solving this? Now that externals can be imported with ESM, I think it’s important to make sure webpack treats the externals properly.
Issue Analytics
- State:
- Created 3 years ago
- Comments:6 (6 by maintainers)
Top GitHub Comments
Thanks for the response - I’ll try to put together a PR for this.
Yes
Sure - am happy to do that.
That’s a good question - I hadn’t thought about that. Live bindings should still work because my implementation use getters to the original module namespace object. However, referential equality checks would be broken:
Hey. Sorry, I have not yet found some time to review/study this. Will try to get to it soon.
Paul T. – Sent from Mobile