Dschungelabenteuer / vite-plugin-entry-shaking

Mimic tree-shaking behaviour when importing code from an entry file in development mode.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

TypeScript doesn't recognize esm exports of this package

tscpp opened this issue · comments

Note
See #20 (comment) first.

Describe the bug A clear and concise description of what the bug is.

Note
This bug affects the type checking in vite.config.ts has nothing to do with the plugin itself.

I am using "module": "Node16" in my tsconfig.json which also implies "moduleResolution": "Node16". The "Node16" module resolution needs to identify this package as an ESM compatible module to be able to handle the exports type correctly.

However, because this package doesn't have a "module": "..." field the "Node16" module resolution recognizes this package as a CommonJS module, which causes all exports to be named, including the default exports.

It seems to be caused by having the "types": "..." field in the "exports" field. I tried to remove the "types" field from "exports", and it suddenly worked. I have no idea why.

So in my case, this happens:

import EntryShakingPlugin from 'vite-plugin-entry-shaking';

// This expression is not callable.
//  Type 'typeof import(".../node_modules/vite-plugin-entry-shaking/dist/index")' has no call signatures.
await EntryShakingPlugin(...);

// Type-checking succeeds, runtime does not.
await EntryShakingPlugin.default(...),

// I get the same when doing:
import { default as EntryShakingPlugin } from 'vite-plugin-entry-shaking';
await EntryShakingPlugin(...);

// And:
import EntryShakingPlugin from 'vite-plugin-entry-shaking';
await EntryShakingPlugin.default(...);

To Reproduce Steps to reproduce the behavior:

  1. Create a tsconfig.json with "module": "Node16".
  2. Try importing the default export.

Expected behavior A clear and concise description of what you expected to happen.

The package should include a "module": "..." field in order for TypeScript to recognize the package as an ESM module.

I think this may deserve an issue in TypeScript. But for now, removing "exports.types" would fix this issue.

One solution I found working was to set "type": "module".

Alternatively, or additionally, export EntryShakingPlugin as a named export in addition to the default export. This also improves other aspects too. See https://basarat.gitbook.io/typescript/main-1/defaultisbad.

I accidentally posted the issue when it was incomplete. I edited the issue after posting it. If you are reading from email, it might not be up to date. Sorry for any incontinence.

I have created two pull requests which both addresses this issue. Feel free to close or merge either or both of them.

As I mentioned in #21, I went down the wrong rabbit hole. I realized how stupid my issue was. I am closing this issue but leaving #22 open if it is wanted.