hyrious / hyrious

me
0 stars 0 forks source link

Dual Package is Too Heavy #30

Open hyrious opened 6 months ago

hyrious commented 6 months ago

Dual CommonJS/ES module packages are a way to publish both ESM and CJS library in one package. This is a very common practice for many modern packages but I found it sometimes sucks in many ways. For which in the end I may just prefer Pure ESM.

In summary, it is maybe only painless in the below cases to use dual packages:

hyrious commented 6 months ago

Note: for the first problem -- multiple instances. A solution in TypeScript is to only export types that having no JS entities. For example, do not export a class, but export the interface and a function isInstanceOfType to support checking types.

export interface Dog { bark(): void }

class DogImpl implements Dog { bark() {} }

export function createDog(): Dog { return new DocImpl }

export function isDog(a: any): a is Dog {
  return a && typeof a.bark == 'function'
}

Interfaces can be compatible with each other even in different versions of one package, while classes can not because they may refer to different classes that having the same name. That is to say, classes are bound to its file path while interfaces are not.