planttheidea / fast-copy

A blazing fast deep object copier
MIT License
1.13k stars 31 forks source link

cjs and esm distribution export inconsitency #37

Closed maximilianMairinger closed 3 years ago

maximilianMairinger commented 3 years ago

dist/fast-copy.cjs.js exports

module.exports = copy

and dist/fast-copy.esm.js exports

export default copy

Request: Make dist/fast-copy.cjs.js export on default as well

module.exports = copy
copy.default = copy
maximilianMairinger commented 3 years ago

Id be happy to help if you could give me a quick intro into how you build

planttheidea commented 3 years ago

What is the problem you are trying to solve?

maximilianMairinger commented 3 years ago

@planttheidea Thanks for the quick response.

Some of my packages provide a cjs and esm build. I use typescript with the compiler option "module": "esnext" (for esm) / "module": "commonjs" (for cjs) to transpile to the different targets. My packages are written in esm and import this library with import clone from "fast-copy" (as described in your type declaration) thus targeting the default export. When this gets transpiled to esm nothing changes, regarding the imports and it works properly (as the build fast-copy.esm.js exports export default copy). Only when it gets transpiled to cjs, typescript resolves my import clone from "fast-copy" as const clone = require("fast-copy").default (correctly, as I imported the default). But now (since it's required) fast-copy.cjs.js is imported, which doesn't provide a default export.

I understand the concern that "only cjs users" do not want to write const clone = require("fast-copy").default but rather const clone = require("fast-copy"), but this breaks compatibility for build scripts. My suggestion would be to export on default as well as the main export in the cjs build. Thus:

module.exports = copy
copy.default = copy

Doing it the other way around is to the best of my knowledge not possible, as there is no way to declare a main export in esm (nor as way to type it with typescript).

planttheidea commented 3 years ago

In doing some investigation, it looks like this is specific to using TSC as a compiler (Babel does not have this issue), and was intentional architectural decision! Sometimes I don't understand the rigidity that TS maintainers have about some opinions, but whatever.

I think you're idea is a reasonable "least bad" option. I can make this change.

planttheidea commented 3 years ago

This should be available as-of 2.1.1. If you have any issues, let me know!

maximilianMairinger commented 3 years ago

Great, thanks! I didn't know that this was a tsc specific issue, sorry.