nodejs / modules

Node.js Modules Team
MIT License
413 stars 42 forks source link

Synthetic modules #546

Open dfabulich opened 4 years ago

dfabulich commented 4 years ago

I really liked dynamic modules; it's too bad they didn't get anywhere with TC39. I have an idea that might accomplish something similar without requiring TC39 approval.

Today, in Node 14.8, when a user attempts to import {foo} from './bar.cjs', it fails with this error message:

SyntaxError: The requested module './bar.cjs' is expected to be of type CommonJS,
which does not support named exports. CommonJS modules can be imported by
importing the default export.
For example:
import pkg from './bar.cjs';
const {foo} = pkg;

That's pointless busy work for the end user. Why doesn't Node just do it for me? When Node encounters a named import from CJS, Node could synthesize an ES module containing that exact text, feed it to V8, and run it.

import pkg from './bar.cjs';
if (!('foo' in pkg)) throw new Error(`[CJS_MISSING_EXPORT] The requested module './bar.cjs' does not provide an export named 'foo'`);
export const {foo} = pkg;

What about star exports from CJS?

Today in Node 14.8, export * from './bar.cjs' "succeeds," exporting no names, which is useless. I've filed a separate issue #545 on that. I propose to either fix that bug or, if necessary, leave the star export CJS behavior as is, exporting no names. Either way, it would not be a regression from Node 14.