Skip to content

[Bug]: Importing 'default' export from e.g. @babel/generator does not work in ESM with TS #15269

@devversion

Description

@devversion

💻

  • Would you like to work on a fix?

How are you using Babel?

Programmatic API (babel.transform, babel.parse)

Input code

TypeScript file written as ESM. using e.g. test.mts

import generate from '@babel/generator';

// generate is typed as the function.
generate(bla)

Configuration file name

No response

Configuration

No response

Current and expected behavior

There is no way to import @babel/generator (or others) in an ESM compatible way because:

  • the d.ts from Babel declares export default function
  • but in practice the JS is exports.default = function() ..

If imported via ESM, since @babel/generator is a CommonJS module, all named exports are exposed as a default export. So in practice the generate variable from import generate from '@babel/generator is an object with a property default.

This causes failures like:

TypeError: generate is not a function

Expected behavior:

Babel ships ESM variant of their tooling using NodeJS package exports, or their type definitions do not suggest a default export (although I don't think there can be a named binding called default)

Environment

  System:
    OS: Linux 5.19 Debian GNU/Linux rodete 12 (rodete)
  Binaries:
    Node: 16.14.2 - ~/bin/node/bin/node
    Yarn: 1.22.17 - ~/bin/node/bin/yarn
    npm: 8.19.2 - ~/bin/node/bin/npm
  npmPackages:
    @babel/cli: 7.19.3 => 7.19.3 
    @babel/core: 7.19.3 => 7.19.3 
    @babel/generator: 7.19.5 => 7.19.5 
    @babel/parser: 7.19.4 => 7.19.4 
    @babel/preset-env: 7.19.4 => 7.19.4 
    @babel/template: 7.18.10 => 7.18.10 
    @babel/traverse: 7.19.4 => 7.19.4 
    @babel/types: 7.19.4 => 7.19.4 

Possible solution

Babel would ship an ESM-compatible output flavor in their packages. Best used in combination with NodeJS package.json exports.

Additional context

Related to #12363 I assume.
Also #13855 (comment) (maybe it should be kept for tracking?)

Metadata

Metadata

Assignees

No one assigned

    Labels

    i: needs triageoutdatedA 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