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

Provide a way for CommonJS scripts to synchronously import ESM #520

Closed
dfabulich opened this issue May 27, 2020 · 2 comments
Closed

Provide a way for CommonJS scripts to synchronously import ESM #520

dfabulich opened this issue May 27, 2020 · 2 comments

Comments

@dfabulich
Copy link

Today, it's straightforward to take a CJS library and add an ESM wrapper around it; this is recommended practice in https://github.com/nodejs/node/blob/master/doc/api/esm.md

// ./node_modules/pkg/wrapper.mjs
import cjsModule from './index.cjs';
export const name = cjsModule.name;

But, as far as I can tell, there's no way to write a synchronous CJS wrapper around an ESM library. CJS scripts can only import ESM with asynchronous dynamic import.

I believe I understand why require('./index.mjs') wouldn't match the CJS require semantics, but I think it should be possible in principle to implement a module.importSync() feature that would work like this:

// ./node_modules/pkg/wrapper.cjs
const {importSync} = require('module');
const {name} = importSync('./index.mjs');
module.exports.name = name;

This feature would be useful, because it would provide a path for a CJS library to port to ESM while preserving CJS semantics. A typical flow might be:

  1. Pure CJS library
  2. Add ESM wrapper and exports map in package.json
  3. Port to ESM, add CJS wrapper, update exports map
@GeoffreyBooth
Copy link
Member

I think that your importSync would run into the same issues as “require of ESM” which has had a lot of discussion in this repo and a PR from @weswigham. See #454.

@dfabulich
Copy link
Author

Thanks, I think I get it now. (The core problem is that index.mjs may or may not use top-level await.)

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

2 participants