Use cases 2, 10, 39, 41.
I had a idea about how to achieve this, for the use case where my package is already fully migrated into ESM syntax. So the easy way, that doesn鈥檛 fulfill all the goals of the feature request, would be to have my app include a build step that transpiles it into CommonJS. The CommonJS version is what I publish to NPM and have package.json tell other packages to import. That鈥檚 what people do today.
So how to achieve this without a build step? Well, what if we borrow some ideas from #81 and #101 and https://github.com/nodejs/node/pull/18392 and https://github.com/rollup/rollup/wiki/pkg.module?
package.json would have a main key that points to a CommonJS entry point, and a module key that points to an ESM entry point (or other key names to be decided upon).main CommonJS entry point would have something like require('babel/register') and then would require the ESM entry point. This would allow my package to be imported by legacy versions of Node that lack ESM support, without the code being transpiled ahead of time.module ESM entry point would be used by modern, ESM-supporting Node, and would bypass the main entry point (which is essentially just an ESM polyfill).The polyfill in the CommonJS entry point doesn鈥檛 need to be Babel, and it doesn鈥檛 (necessarily) need to transpile, if other solutions can be found. But let鈥檚 say that at least the above approach works. The downside of this is that for non-ESM-supporting runtimes, whatever the polyfill is (transpilation, etc.), it鈥檒l surely be slower than if we had transpiled the package ahead of time and published it as native CommonJS. That鈥檚 the disadvantage of polyfills in general. But as ESM support becomes more common, this performance hit for legacy runtimes will become less important.
you can just do main: 'src/index' and it will pick up src/index.mjs for esm and src/index.js for cjs
I would prefer to have two keys and drop .mjs.
@GeoffreyBooth two keys doesn鈥檛 address deep paths; mjs will be necessary for ensuring that all files can be consumed by all consumers.
Most helpful comment
@GeoffreyBooth two keys doesn鈥檛 address deep paths; mjs will be necessary for ensuring that all files can be consumed by all consumers.