Skip to content

Bug: require() doesn't support default exports in ES Modules #4742

Closed

Description

@fregante

✅ ➡️ Edit 2020 for Webpack users:

  • 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?

const ofi = 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.

npm i [email protected]
npm i [email protected] --global
echo 'var ofi = require("object-fit-images"); ofi()' > src.js; webpack src.js errors.js
echo 'var ofi = require("object-fit-images").default; ofi()' > src.js; webpack src.js works.js
echo 'import ofi from "object-fit-images"; ofi()' > src.js; webpack src.js works-esm.js

What is the expected behavior?

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

Activity

  1. sokra commented on Apr 19, 2017

    @sokra
    Member

    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.

  2. fregante commented on Apr 19, 2017

    @fregante
    ContributorAuthor

    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:

    var webpack = require('webpack').default; //<--
    webpack(...);
    //or
    var webpack = 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:

    echo 'var ofi = require("object-fit-images"); ofi()' > src.js; webpack src.js dist.js
    echo 'import ofi from "object-fit-images"; ofi()' > src.js; webpack src.js dist.js
  3. fregante commented on Apr 19, 2017

    @fregante
    ContributorAuthor

    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.

    You're perfectly right here, always read one file regardless of which import/require method is used.

    So how about flattening the default export with interopDefault like babel and rollup do?

    webpack could automatically change this:

    var ofi = require("object-fit-images");
    ofi();

    into:

    var ofi = require("object-fit-images");
    ofi = 'default' in ofi ? ofi['default'] : ofi;
    ofi();
  4. added a commit that references this issue on Apr 19, 2017
  5. changed the title [-]Bug: require() loads `module` instead of `main`[/-] [+]Bug: require() doesn't support `default` exports in ES Modules[/+] on Apr 19, 2017
  6. sokra commented on Apr 19, 2017

    @sokra
    Member

    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.

    export default <=> exports.default =
    export function test() <=> exports.test = function()
    N/A <=> module.exports

  7. fregante commented on Apr 20, 2017

    @fregante
    ContributorAuthor

    No other CommonJs impl does something like you proposed and it doesn't make sense.

    1. 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)

    2. rollup does that when requiring es modules:

      $ cat module.js 
      export default function foo () {}
      
      $ cat requirer.js 
      const test = require('./module.js');
      console.log(test)
      
      $ cat rollup.config.js 
      export default {
        format: 'cjs',
        plugins: [ require('rollup-plugin-commonjs')() ]
      };
      
      $ rollup requirer.js --config | node
      [Function: foo] # this is console.log(test)
    3. 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?

    const webpack = 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.

  8. added a commit that references this issue on Apr 29, 2017
  9. tivac commented on May 8, 2017

    @tivac

    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. 😓

  10. fregante commented on May 9, 2017

    @fregante
    ContributorAuthor

    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:

    • 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.

  11. added a commit that references this issue on Oct 5, 2017
  12. 18 remaining items

  13. TrySound commented on Feb 12, 2019

    @TrySound
    Contributor

    Why not this? Always works for me without any tricks and api is the same on both sides.

    import { produce } from 'immer'
  14. mweststrate commented on Feb 12, 2019

    @mweststrate

    yes, that is what I would have done if I had learned this lesson before using the default export 😅

  15. fregante commented on Feb 12, 2019

    @fregante
    ContributorAuthor

    @mweststrate that’s probably the most reasonable and easily-documentable solution.

    ...but it's still better to not use the module field.

  16. added a commit that references this issue on Mar 8, 2019
  17. added a commit that references this issue on Mar 14, 2019
  18. jablko commented on Apr 3, 2019

    @jablko

    Hrm ... So I've got:

    • 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?
    • It seems like what I want is libraryExport: "default" for dependency A vs. the output?

    What's the best solution?

  19. AndreasEK commented on Jun 26, 2019

    @AndreasEK

    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.

  20. maxkfranz commented on Sep 23, 2019

    @maxkfranz

    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.

  21. prusswan commented on Sep 24, 2019

    @prusswan

    @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

  22. lygstate commented on Oct 10, 2020

    @lygstate

    anyway to fixes this in webpack???
    too much packages have such issues, broken again and again.

  23. lygstate commented on Oct 10, 2020

    @lygstate

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions