davidbonnet / astring

🌳 Tiny and fast JavaScript code generator from an ESTree-compliant AST.

Home Page:https://david.bonnet.cc/astring/demo/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Version 1.7.3 breaks imports

remcohaszing opened this issue · comments

Motivation

The following script worked using astring@1.7.2, but is broken using astring@1.7.3:

import { baseGenerator, generate } from 'astring';

Expected behavior

Nothing happens

$ node script.mjs
$

Actual behavior

Node crashes

$ node script.mjs
file:///home/remco/Downloads/foo/script.mjs:1
import { baseGenerator, generate } from 'astring';

SyntaxError: Named export 'generate' not found. The requested module 'astring' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'astring';
const { baseGenerator, generate } = pkg;

    at ModuleJob._instantiate (internal/modules/esm/module_job.js:104:21)
    at async ModuleJob.run (internal/modules/esm/module_job.js:149:5)
    at async Loader.import (internal/modules/esm/loader.js:166:24)
    at async Object.loadESM (internal/process/esm_loader.js:68:5)
commented

/cc @davidbonnet The above error is I think hiding what’s actually going on.
The new exports map breaks anyone using ESM, so an import to load astring: they’ll get src/astring.js, but because that files closest package.json does not have a type: 'module', it’s seen as CJS.

If I do:

import astring from 'astring'

Node will crash:

~/xdm/node_modules/astring/src/astring.js:57
export const NEEDS_PARENTHESES = 17
^^^^^^

SyntaxError: Unexpected token 'export'
    at Object.compileFunction (node:vm:355:18)
    ...

Thanks a lot @remcohaszing for reporting this embarrassing 😳 issue, and @wooorm for providing insights.