Skip to content
This repository has been archived by the owner on Sep 2, 2023. It is now read-only.

Synthetic modules #546

Open
dfabulich opened this issue Aug 15, 2020 · 0 comments
Open

Synthetic modules #546

dfabulich opened this issue Aug 15, 2020 · 0 comments

Comments

@dfabulich
Copy link

dfabulich commented Aug 15, 2020

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant