webpackbar icon indicating copy to clipboard operation
webpackbar copied to clipboard

fix: make package.json exports field compatible with TS NodeNext

Open Josh-Cena opened this issue 3 years ago • 0 comments

To be fair, I'm not entirely sure what the best practice here is😅

Under the status quo, when you try to compile a file (which will be compiled to a CJS module) containing:

import WebpackBar from 'webpackbar';

And with tsconfig.json:

{
  "compilerOptions": {
    "module": "NodeNext"
  }
}

TS errors that it can't find a declaration file for webpackbar, because the respective exports entry does not have a types field, and TS won't fall back to the root types field (for some reason).

If you simply add a types field to each exports field, TS now errors that "Module 'webpackbar' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported synchronously. Use dynamic import instead." This is because the root package.json has a "type": "module" field, and the require override doesn't seem to be respected (https://github.com/microsoft/TypeScript/issues/49299).

I figured out in the end that the best way may be to simply remove the "type": "module" field so that the declaration can at least be interpreted as a CJS declaration, which will work in both CJS and ESM. Since the two dist files both have explicit extensions, this shouldn't cause any issues.

There's some reference here: https://devblogs.microsoft.com/typescript/announcing-typescript-4-7/#package-json-exports-imports-and-self-referencing But I failed to find a comprehensive guide in any docs.

Josh-Cena avatar Jun 09 '22 09:06 Josh-Cena