unplugin / unplugin-auto-import

Auto import APIs on-demand for Vite, Webpack and Rollup
MIT License
3.29k stars 198 forks source link

Declaration of files with suffixes is incorrect #458

Open AntonyZ89 opened 11 months ago

AntonyZ89 commented 11 months ago

Describe the bug

Hi, I'm facing an issue with the auto-import.d.ts file when generating files with the suffixes as: foo.composable.ts or bar.helper.ts, etc.

The problem is that the file removes the suffix, which causes an "any" type for my files, specifically within the declare global {} block. I've tried investigating the issue on my own but can't seem to understand the problem. Below, I'll list what I have attempted.

Problem: image

What solved my problem was changing this line in the unplugin/unimport library:

function toTypeDeclarationItems(imports, options) {
  return imports.map((i) => {
+    const from = options?.resolvePath?.(i) || (i.typeFrom || i.from).replace(/\.[a-zA-Z]+$/, "");
-    const from = (options?.resolvePath?.(i) || i.typeFrom || i.from).replace(/\.[a-zA-Z]+$/, "");
    return `const ${i.as}: typeof import('${from}')${i.name !== "*" ? `['${i.name}']` : ""}`;
  }).sort();
}

However, when I forked the unplugin/unimport repository to create a pull request, it broke all tests hahaha. So, the issue might not be related to this change, or it could be happening due to how I am using the library.

So, I forked the unplugin-auto-import repository and tried to reproduce my problem. Surprisingly, everything worked well in the playground folder.

Lastly, I created a project on StackBlitz and another on my computer using bun create vite, and both exhibited the same problem I'm facing in my project.


To reproduce the error, run rm auto-import.d.ts; npm run build

Observe how the file is generated: foo.composable.ts is written as foo instead of foo.composable within the declare global {} block.

Reproduction

https://stackblitz.com/edit/vue3-vite-starter-srm5lm

System Info

System:
    OS: Linux 6.6 Arch Linux
    CPU: (12) x64 AMD Ryzen 5 5600X 6-Core Processor
    Memory: 19.51 GB / 31.25 GB
    Container: Yes
    Shell: 5.9 - /usr/bin/zsh
  Binaries:
    Node: 18.12.0 - ~/.asdf/installs/nodejs/18.12.0/bin/node
    Yarn: 1.22.19 - ~/.asdf/installs/nodejs/18.12.0/bin/yarn
    npm: 10.2.0 - ~/.asdf/plugins/nodejs/shims/npm
    pnpm: 8.12.0 - ~/.asdf/installs/nodejs/18.12.0/bin/pnpm
    bun: 1.0.11 - ~/.bun/bin/bun
  Browsers:
    Chromium: 120.0.6099.71

Used Package Manager

pnpm

Validations

stackblitz[bot] commented 11 months ago

Fix this issue in StackBlitz Codeflow Start a new pull request in StackBlitz Codeflow.

userquin commented 11 months ago

Maybe you can use basename(filename, extname(filename)) instead regexp.

Anyway, you sould use kebab or camel case for the file names.