The Node documentation on ECMAScript Modules makes recommendations for "dual packages" that provide both CommonJS scripts and ES module scripts to users.
Specifically, they suggest transpiling ES module scripts to CommonJS, then using an "ES module wrapper", an ES module script that imports from CJS and re-exports its CJS named exports as ESM named exports.
// ./node_modules/pkg/wrapper.mjs
import cjsModule from './index.cjs';
export const name = cjsModule.name;
My question is: is it possible to do this the opposite way, providing my scripts in ES module format, but adding a simple wrapper file in CommonJS allowing CJS users to require
it?
For my part, I can't see a way to do this in synchronous code. It appears to me that CommonJS scripts can only import ES modules via asynchronous dynamic import()
.
(async () => {
const {foo} = await import('./foo.mjs');
})();
But that means my CJS script can't export anything that depends on foo
.
import {foo} from './foo.cjs'
, but I want to know whether CommonJS canconst {foo} = importSync('./foo.mjs')
(or, if not, why not) – Dan FabulichimportSync
would need to transpile code on the fly. – Yury Tarabankoimport()
to import ESM in CJS in Node 14, without transpiling. I just want to do it synchronously. – Dan Fabulich