require() prefers ES Modules?
See original GitHub issueIs this a bug report?
Yes, I think this is a bug report.
Did you try recovering your dependencies?
Yes, and this bug doesn’t have anything to do with installing dependencies.
Which terms did you search for in User Guide?
- ES Modules
- require
- CommonJS
Environment
➜ cra git:(master) ✗ npx create-react-app --info
npx: installed 63 in 1.784s
Environment Info:
System:
OS: macOS 10.14.2
CPU: x64 Intel(R) Core(TM) i7-8559U CPU @ 2.70GHz
Binaries:
Node: 10.14.1 - ~/n/bin/node
Yarn: 1.9.4 - ~/.yarn/bin/yarn
npm: 6.7.0 - /usr/local/bin/npm
Browsers:
Firefox: 64.0.2
Safari: 12.0.2
npmPackages:
react: ^16.7.0 => 16.7.0
react-dom: ^16.7.0 => 16.7.0
react-scripts: 2.0.3 => 2.0.3
npmGlobalPackages:
create-react-app: Not Found
Steps to Reproduce
(Write your steps here:)
- Write a module that you want people to use, providing it as a CommonJS module.
- Try to modernize the module, and provide an ES Module entry point, exposing it under
module
. This feels, to you, like a minor change: you’re adding something. - Your users use the module with create-react-app and
require()
. require(), for some reason, loads the ES Module now, not the CommonJS module, and in the unfortunate haphazard way that the two interop, it is now ‘broken’, and the require() returns an object with{default:fn()}
instead offn()
as it did before.
Expected Behavior
I assumed that the CommonJS syntax require() would use the CommonJS entry point, and the ES Module import would use the ES Module entry point, and that this wouldn’t be a breaking change.
Actual Behavior
The module appears to be ‘broken’ to people consuming it via create-react-app - and possibly all similar webpack-related toolchains.
As a module maintainer, this leaves me with no clear way to introduce ES Module entry points into my modules without breaking them for CommonJS users. And I can’t see why this behavior - apparently preferring the module
entry point to the main
one even through require()
would be default.
Reproducible Demo
One-commit demo is at https://github.com/tmcw/cra-example
The one commit is https://github.com/tmcw/cra-example/commit/c1262372fba3104f25d6dad3d77c37b0ad8a4442 which adds a dependency, uses it with require()
and console.logs it.
Issue Analytics
- State:
- Created 5 years ago
- Comments:12 (6 by maintainers)
Top GitHub Comments
? tree-shaking works fine on commonjs modules too using https://github.com/indutny/common-shake The zeal for ES modules without enough regard for interop and backwards compat has caused so many problems, like this one.
@tmcw there’s a webpack issue here https://github.com/webpack/webpack/issues/5756
From 2017.
@sokra said “won’t fix”
And there’s another one from 2018 that’s pretty much the same thing with the same response: https://github.com/webpack/webpack/issues/6584