pkg.main, pkg.module are incompatible, so require("quickselect") behaves differently under Rollup/Webpack #11
Description
In Node, require("quickselect")
returns the function quickselect
, but in Webpack, require("quickselect")
returns a module { default: quickselect }
. This means a quickselect
dependent can’t be compatible with both environments without contortions.
$ echo 'console.log(require("quickselect"))' > src.js
$ npm i quickselect webpack webpack-cli
$ node src.js
[Function: quickselect]
$ npx webpack -d
$ node dist/main.js
Object [Module] { default: [Getter] }
This is because Node is using pkg.main
(quickselect.js
) and Webpack is using pkg.module
(index.js
), and the two files do not provide compatible interfaces.
This problem is called out in the Rollup documentation:
Note: There are some tools such as Babel, TypeScript, Webpack, and
@rollup/plugin-commonjs
that are capable of resolving a CommonJSrequire(...)
call with an ES module. If you are generating CommonJS output that is meant to be interchangeable with ESM output for those tools, you should always usenamed
export mode. The reason is that most of those tools will by default return the namespace of an ES module onrequire
where the default export is the.default
property.
This was previously touched on in #6, but only in the context of the current quickselect
in Webpack being incompatible with an old quickselect
in Webpack (resolved by bumping the major version), not the current quickselect
in Webpack being incompatible with the current quickselect
in Node (still an issue).
Three potential solutions are:
- use
named
export mode, sorequire("quickselect").default
would work everywhere; or - add
quickselect.default = quickselect
for compatibility; or - remove
pkg.module
.