Skip to content

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

@fregante

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 object-fit-images@3.1.3
npm i webpack@2.4.1 --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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions