Skip to content

@babel/plugin-transform-modules-commonjs incorrectly assumes default exists when importing an __esModule #7998

@jaydenseric

Description

@jaydenseric

Bug Report

When running native ESM in Node.js (via .mjs) you are supposed to be able to use an ESM default import to import the module exports of a CJS module:

https://nodejs.org/api/esm.html#esm_interoperability_with_commonjs

Babel will cause the default import to be undefined at runtime in the following situation:

  • Your source is ESM being compiled with @babel/plugin-transform-modules-commonjs.
  • The CJS being imported was compiled for distribution using Babel from ESM named exports without a default export. The CJS module exports __esModule but no default.

Input Code

Input:

// Contains CJS with __esModule, but no default.
import graphql from 'graphql/index.js'

// Should not log undefined.
console.log(graphql.GraphQLSchema)

Flawed output:

"use strict";

var _index = require("graphql/index.js");

var _index2 = _interopRequireDefault(_index);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

console.log(_index2.default.GraphQLSchema);

Expected behavior/code

At runtime, GraphQLSchema should log instead of undefined.

Babel Configuration (.babelrc, package.json, cli command)

Default usage of @babel/plugin-transform-modules-commonjs or @babel/preset-env.

Environment

  • Babel version(s): v7.0.0-beta.47
  • Node/npm version: Node v10.1.0/npm v6.0.1
  • OS: [e.g. OSX 10.13.4, Windows 10]
  • Monorepo: No
  • How you are using Babel: cli

Possible Solution

Additional context/Screenshots

The example input demonstrates a workaround to graphql/express-graphql#425.

Metadata

Metadata

Assignees

No one assigned

    Labels

    outdatedA closed issue/PR that is archived due to age. Recommended to make a new issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions