This is a gigantic hack but it seems to work, until ECMAScript modules (ESM) are more widely supported. Many npm modules are already published as ECMAScript modules but not all apps could import them. Iʼm using it on one of my Gatsby sites.
The idea is to use esbuild to compile ESM files to CommonJS directly inside the node_modules folder on npm install. We’ll detect packages that need to be compiled by checking that the type filed in the package.json has the module value.
Add dependencies:
npm install -D tiny-glob esbuild
Add a new script, scripts/esmtocjs.js
Add a postinstall script to the package.json:
Now, every time we run npm install, all ESM files inside node_modules will be compiled to CommonJS, so they could be imported by Gatsby or any other tool that doesn’t yet support ESM.