[Pkg-javascript-devel] Export both ESM and CommonJS modules

Pirate Praveen praveen at onenetbeyond.org
Sun Sep 12 17:35:19 BST 2021



On ഞാ, സെപ്റ്റം 12, 2021 at 18:29, Yadd 
<yadd at debian.org> wrote:
> Hi all,
> 
> some recent updates switched from CommonJS to ESM ("type: module"). I
> found a way for node-strip-json-comments which can be applied to most 
> of
> Sindre Sorhus modules:
> 
>  1. build a commonjs file:
> 
> 	babeljs -o index.cjs index.js
> 	perl -i -pe 's/^export default/module.exports =/' index.cjs
> 
>  2. adapt package.json:
> 
> 	--- a/package.json
> 	+++ b/package.json
> 	@@ -11,7 +11,12 @@
> 	  		"url": "https://sindresorhus.com"
> 	  	},
> 	  	"type": "module",
> 	-	"exports": "./index.js",
> 	+	"exports": {
> 	+		"import": "./index.js",
> 	+		"require": "./index.cjs"
> 	+	},
> 	+	"main": "./index.cjs",
> 	+	"module": "./index.js",
> 	  	"engines": {
> 	  		"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
> 	  	},
> 	@@ -20,6 +25,7 @@
> 	  		"bench": "matcha benchmark.js"
> 	  	},
> 	  	"files": [
> 	+		"index.cjs",
> 	  		"index.js",
> 	  		"index.d.ts"
> 	  	],
> 
> For more complex packages, see
> https://www.sensedeep.com/blog/posts/2021/how-to-create-single-source-npm-module.html

I don't think this approach (tryng to support two versions of 
everything) is really sustainable, for one or two packages it would be 
fine. We should look at it like any breaking major version update and 
try to update reverse dependencies to new APIs (switch to import from 
require) and only if that is too much work, we should try to support 
both versions.

With nodejs supporting ESM natively, we should try to avoid as much of 
build steps as possible.





More information about the Pkg-javascript-devel mailing list