unjs / webpackbar

Elegant ProgressBar and Profiler for Webpack 3 , 4 and 5
MIT License
2.07k stars 66 forks source link

build: add types export conditions #108

Closed Josh-Cena closed 11 months ago

Josh-Cena commented 2 years ago

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.

markscamilleri commented 1 year ago

I have literally just encountered this issue too, so I admit it's a bit disheartening to see the PR has been open for almost a year. @Josh-Cena I believe the PR does still work - though with my setup I was able to fix without removing "type": "module", but I am using the following in my tsconfig.json:

    "module": "es2022",
    "moduleResolution": "bundler",

@pi0 not sure who to tag, but is this a change that can be added to the package? I don't see how it could break anything - but maybe it might be worth testing it out on other configurations? The package.json in master, with my configuration TypeScript errors with the following:

Could not find a declaration file for module 'webpackbar'. '{{project}}/node_modules/webpackbar/dist/index.mjs' implicitly has an 'any' type.
  There are types at '{{project}}/node_modules/webpackbar/dist/index.d.ts', but this result could not be resolved when respecting package.json "exports". The 'webpackbar' library may need to update its package.json or typings.ts(7016)