You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Bug: require() doesn't support default exports in ES Modules #4742
always prefer import nowadays. Only use require if the package is not an ES Module.
Do you want to request a feature or report a bug?
Bug
What is the current behavior?
constofi=require('object-fit-images');
In webpack 1.x, this picks up the CommonJS file defined in main.
In webpack 2.x, this loads the module file and sets ofi = {default: realOfi}, which means that users have to use the unnatural const ofi = require('object-fit-images').default. Example
If the current behavior is a bug, please provide the steps to reproduce.
import is for ES Modules and it should try to read the module file if it exists. This works correctly.
require is for CJS files and it should only read the main entry point, not the module one. If it does, it should at least flatten default wherever possible.
Please mention other relevant information such as the browser version, Node.js version, webpack version and Operating System.
node 7.8.0
webpack 2.4.1
OSX 10.11.6
Reacted by Pat Cavit, Bart Van Beurden, Réda Housni Alaoui, Volodymyr Agafonkin, Denma Syarikin, Andrew Lisowski, Andreas, swyx.io, Michał Gołębiowski-Owczarek, S E R A Y A and 24 more
Reacted by Evan Jacobs, Adrian Pascu, Matthew Borden and Alan Plum
Packages should not export different things from module and main.
The main/module fields in the package.json describe the entrypoint of the package in ESM and CJS. It doesn't depend on the way you require/import it.
If if would depend on it, it would cause duplication i. e. if you require a module in one file and import it in another file.
So in my opinion this is working correctly. But like to hear more opinions...
I know this is bad for package author because this could mean they need to break the API when adding a ESM export. i. e. when previously exporting a function with module.exports = function objectFitImages() {} they need to change their API to exports.objectFitImages = function() {} or default. objectFitImages = require("object-fit-images") -> objectFitImages = require("object-fit-images").objectFitImages or objectFitImages = require("object-fit-images").default.
Packages should not export different things from module and main.
That makes sense, but in reality neither of those options is ideal. You wouldn't expect anyone to use something like this:
varwebpack=require('webpack').default;//<--webpack(...);//orvarwebpack=require('webpack');webpack.webpack(...);//<-- almost ok, but awkward
It defeats the purpose of having a separate module file at all since it only complicates things when using default exports. Without module both of these work as expected:
changed the title [-]Bug: require() loads `module` instead of `main`[/-][+]Bug: require() doesn't support `default` exports in ES Modules[/+]on Apr 19, 2017
interopDefault happens when importing a CommonJs module. webpack does the same. No other CommonJs impl does something like you proposed and it doesn't make sense. You won't be able to access other exports except the default export.
The purpose of the module field is to offer the same package content with ESM instead of CJS. You are using it wrong if you put different APIs behind the module field. Exports should match.
No other CommonJs impl does something like you proposed and it doesn't make sense.
It makes sense to me since both a = require() and import a from mean get the default export ("default" in the classical sense, not how it's described by the ESM spec)
rollup does that when bundling exporting modules, export default X becomes module.exports = X, demo
The purpose of the module field is to offer the same package content
I already agreed with that in my previous comment.
What I'm suggesting is the equivalent of interopDefault when requiring ES default imports. Would you ever suggest using this API for your own modules?
constwebpack=require('webpack').default;
.default should never be part of an API.
Now we could even agree that the current situation makes perfect technical sense, but this kills interoperability: it either results in poor APIs (.default) or into the unusability of the module field for default-exporting modules.
I just ran into this with modular-css after trying to offer named ES2015 exports. Some CSS classnames aren't valid JS identifiers, so they can't be part of the named exports. Now uses will have to use require("./file.css").default if they want access to all exported classnames.
I'm considering reverting the change to use ES2015 exports because of this, it's now a bad experience for end-users. 😓
Reacted by fregante, René Jochum, Rasmus Porsager, Pierre-Yves Gérardy, Travis Fischer and Dong Guo
offer a separate package like lodash does (lodash-es), or
skip the module field and use a es-specific entry point, like import a from 'yourpkg/es'
skip the module field, avoid es modules (my preferred solution for most of my modules)
The first two choices will be explicit and won't depend on tooling (but they'll need to be documented)
The last choice just works with all CommonJS loaders/tools.
a dependency A that package.json -> ["module"] -> export default X
a dependency B that const X = require("A")
Webpack that implements require("A") -> { default: X }
Without getting into fixing any one of these (as far as I can see, if you implement require("A") -> X then in CommonJS you can't require() any named exports, and if you implement require("A") -> { default: X } then from ESM you can't replace the entire module, so ¯\_(ツ)_/¯) how can I configure Webpack?
I'm aware of:
resolve.alias -- I can maybe redirect require("A") to some module.exports = require("A").default shim?
resolve.mainFields -- I can use package.json -> ["main"] vs. ["module"], but not on a per-dependency basis?
I came here, because I stumbled about a problem when using react-datetime and moment. First I read some very old bug reports that were still open, which had a similar issue with moment, although with a different library: palantir/blueprint#959
When you search for "moment ist not a function" you will find a plethora of similar issues. And this is just with one (albeit popular) library. So, from a users perspective, the above discussion is completely missing the point. As a user of react-datetime and moment, and webpack, I now have to patch a library manually, in order to get my setup working.
I can see both sides of this issue. On the one hand, you have the mathematical approach of @mweststrate's table -- looking for equivalence of expressions. That's a natural way to look at things if you're working on a tool like webpack.
On the other hand, a consumer doesn't care about mathematical equivalence. He just cares about the UX of the tools he uses to build his webapps. Does the tool behave as programmer Joe Blow expects, or does the tool surprise him in unpleasant ways? Well, webpack doesn't behave as expected for Joe Blow. Node is his reference point for require(). If it doesn't work like node, Joe considers it broken. He expects webpack to act the same as node when you use require('foo'). It doesn't work the same if you have to do require('foo').default.
Both sides are important. So is there a way to not break with the former while satisfying the latter? The issue exists only on the CJS side. Joe Blow's app code works fine today if he writes it all in ESM with webpack. So we only need to consider CJS apps, whose source is wholly written with require() -- this would probably be most of the existing and legacy apps.
So how do you allow for require('foo') to work with webpack consistently with node? One approach is simple: If you are bundling a CJS app, only pull in CJS main files. If all the source is CJS, you don't have to worry about equivalency of require() to import statements. You can just use require() semantics as defined by node.
If you are bundling a CJS app, there isn't much reason to pull in ESM dependencies: Every package on npm has a CJS main file that already works as expected with require(). And for older or legacy CJS apps, Joe Blow would expect it to be CJS all the way down anyway.
Let the new apps that use ESM get all the new module dependencies and dead code elimination goodies. Legacy CJS apps should just work, even if it's without all the bells and whistles that webpack offers.
@mweststrate those libraries predate webpack. If they are not used with webpack, they will work as intended. Supporting webpack should be a choice, especially when the library authors are not even using webpack themselves
Activity
sokra commentedon Apr 19, 2017
Packages should not export different things from
moduleandmain.The main/module fields in the package.json describe the entrypoint of the package in ESM and CJS. It doesn't depend on the way you require/import it.
If if would depend on it, it would cause duplication i. e. if you require a module in one file and import it in another file.
So in my opinion this is working correctly. But like to hear more opinions...
I know this is bad for package author because this could mean they need to break the API when adding a ESM export. i. e. when previously exporting a function with
module.exports = function objectFitImages() {}they need to change their API toexports.objectFitImages = function() {}ordefault.objectFitImages = require("object-fit-images")->objectFitImages = require("object-fit-images").objectFitImagesorobjectFitImages = require("object-fit-images").default.fregante commentedon Apr 19, 2017
That makes sense, but in reality neither of those options is ideal. You wouldn't expect anyone to use something like this:
It defeats the purpose of having a separate
modulefile at all since it only complicates things when using default exports. Withoutmoduleboth of these work as expected:fregante commentedon Apr 19, 2017
You're perfectly right here, always read one file regardless of which import/require method is used.
So how about flattening the
defaultexport withinteropDefaultlike babel and rollup do?webpackcould automatically change this:into:
Improve webpack 2 usage/compat
[-]Bug: require() loads `module` instead of `main`[/-][+]Bug: require() doesn't support `default` exports in ES Modules[/+]sokra commentedon Apr 19, 2017
interopDefault happens when
importing a CommonJs module. webpack does the same. No other CommonJs impl does something like you proposed and it doesn't make sense. You won't be able to access other exports except the default export.The purpose of the
modulefield is to offer the same package content with ESM instead of CJS. You are using it wrong if you put different APIs behind the module field. Exports should match.export default<=>exports.default =export function test()<=>exports.test = function()N/A <=>
module.exportsfregante commentedon Apr 20, 2017
It makes sense to me since both
a = require()andimport a frommean get the default export ("default" in the classical sense, not how it's described by the ESM spec)rollup does that when requiring es modules:
rollup does that when bundling exporting modules,
export default Xbecomesmodule.exports = X, demoI already agreed with that in my previous comment.
What I'm suggesting is the equivalent of
interopDefaultwhen requiring ES default imports. Would you ever suggest using this API for your own modules?.defaultshould never be part of an API.Now we could even agree that the current situation makes perfect technical sense, but this kills interoperability: it either results in poor APIs (
.default) or into the unusability of themodulefield fordefault-exporting modules.Remove es-modules package
tivac commentedon May 8, 2017
I just ran into this with
modular-cssafter trying to offer named ES2015 exports. Some CSS classnames aren't valid JS identifiers, so they can't be part of the named exports. Now uses will have to userequire("./file.css").defaultif they want access to all exported classnames.I'm considering reverting the change to use ES2015 exports because of this, it's now a bad experience for end-users. 😓
fregante commentedon May 9, 2017
More context: http://2ality.com/2017/01/babel-esm-spec-mode.html#an-es-module-can-only-default-import-commonjs-modules
For library authors: As a workaround, you could:
lodash-es), ormodulefield and use a es-specific entry point, likeimport a from 'yourpkg/es'modulefield, avoid es modules (my preferred solution for most of my modules)The first two choices will be explicit and won't depend on tooling (but they'll need to be documented)
The last choice just works with all CommonJS loaders/tools.
Make ES module opt-in
fix: configure webpack to not use esmodules in dependencies
fix: configure webpack to not use esmodules in dependencies
fix: configure webpack to not use esmodules in dependencies
fix: configure webpack to not use esmodules in dependencies
18 remaining items
TrySound commentedon Feb 12, 2019
Why not this? Always works for me without any tricks and api is the same on both sides.
mweststrate commentedon Feb 12, 2019
yes, that is what I would have done if I had learned this lesson before using the
defaultexport 😅fregante commentedon Feb 12, 2019
@mweststrate that’s probably the most reasonable and easily-documentable solution.
...but it's still better to not use the
modulefield.Fix TypeScript types
improve webpack support
jablko commentedon Apr 3, 2019
Hrm ... So I've got:
Athatpackage.json->["module"]->export default XBthatconst X = require("A")require("A")->{ default: X }Without getting into fixing any one of these (as far as I can see, if you implement
require("A")->Xthen in CommonJS you can'trequire()any named exports, and if you implementrequire("A") -> { default: X }then from ESM you can't replace the entire module, so ¯\_(ツ)_/¯) how can I configure Webpack?I'm aware of:
resolve.alias-- I can maybe redirectrequire("A")to somemodule.exports = require("A").defaultshim?resolve.mainFields-- I can usepackage.json->["main"]vs.["module"], but not on a per-dependency basis?libraryExport: "default"for dependencyAvs. the output?What's the best solution?
AndreasEK commentedon Jun 26, 2019
I came here, because I stumbled about a problem when using react-datetime and moment. First I read some very old bug reports that were still open, which had a similar issue with moment, although with a different library:
palantir/blueprint#959
When you search for "moment ist not a function" you will find a plethora of similar issues. And this is just with one (albeit popular) library. So, from a users perspective, the above discussion is completely missing the point. As a user of react-datetime and moment, and webpack, I now have to patch a library manually, in order to get my setup working.
maxkfranz commentedon Sep 23, 2019
I can see both sides of this issue. On the one hand, you have the mathematical approach of @mweststrate's table -- looking for equivalence of expressions. That's a natural way to look at things if you're working on a tool like webpack.
On the other hand, a consumer doesn't care about mathematical equivalence. He just cares about the UX of the tools he uses to build his webapps. Does the tool behave as programmer Joe Blow expects, or does the tool surprise him in unpleasant ways? Well, webpack doesn't behave as expected for Joe Blow. Node is his reference point for
require(). If it doesn't work like node, Joe considers it broken. He expects webpack to act the same as node when you userequire('foo'). It doesn't work the same if you have to dorequire('foo').default.Both sides are important. So is there a way to not break with the former while satisfying the latter? The issue exists only on the CJS side. Joe Blow's app code works fine today if he writes it all in ESM with webpack. So we only need to consider CJS apps, whose source is wholly written with
require()-- this would probably be most of the existing and legacy apps.So how do you allow for
require('foo')to work with webpack consistently with node? One approach is simple: If you are bundling a CJS app, only pull in CJSmainfiles. If all the source is CJS, you don't have to worry about equivalency ofrequire()toimportstatements. You can just userequire()semantics as defined by node.If you are bundling a CJS app, there isn't much reason to pull in ESM dependencies: Every package on npm has a CJS
mainfile that already works as expected withrequire(). And for older or legacy CJS apps, Joe Blow would expect it to be CJS all the way down anyway.Let the new apps that use ESM get all the new
moduledependencies and dead code elimination goodies. Legacy CJS apps should just work, even if it's without all the bells and whistles that webpack offers.prusswan commentedon Sep 24, 2019
@mweststrate those libraries predate webpack. If they are not used with webpack, they will work as intended. Supporting webpack should be a choice, especially when the library authors are not even using webpack themselves
fix: load typeorm-aurora-data-api-driver correctly when using webpack (…
fix: load typeorm-aurora-data-api-driver correctly when using webpack (…
lygstate commentedon Oct 10, 2020
anyway to fixes this in webpack???
too much packages have such issues, broken again and again.
lygstate commentedon Oct 10, 2020
There is objection, https://www.bignerdranch.com/blog/default-exports-or-named-exports-why-not-both/
I am bitten by these things.
maybe webpack better to provide a optionMap to config each node module are default export or named export.
Fix webpack generation of names for images