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

Yadd yadd at debian.org
Sun Sep 12 17:38:58 BST 2021


Le 12/09/2021 à 18:35, Pirate Praveen a écrit :
> 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.

You're right, but for now this avoid to downgrade updated packages (like
node-strip-json-comments which broke eslint)



More information about the Pkg-javascript-devel mailing list