meowtec / vite-plugin-svg-sprite

SVG sprite plugin for [vite](https://github.com/vitejs/vite)
MIT License
52 stars 10 forks source link

Typings location seems to conflict with package.json exports declaration #18

Closed gburning closed 1 year ago

gburning commented 1 year ago

The error in question:

Could not find a declaration file for module 'vite-plugin-svg-sprite'. '[...]node_modules/vite-plugin-svg-sprite/index.mjs' implicitly has an 'any' type. There are types at '[...]node_modules/vite-plugin-svg-sprite/lib/index.d.ts', but this result could not be resolved when respecting package.json "exports". The 'vite-plugin-svg-sprite' library may need to update its package.json or typings.ts(7016)

npx envinfo --npmPackages '{vite,@vitejs/*,vite-plugin-svg-sprite}' --binaries yields:

  Binaries:
    Node: 18.16.1 - ~/.nvm/versions/node/v18.16.1/bin/node
    npm: 9.5.1 - ~/.nvm/versions/node/v18.16.1/bin/npm
  npmPackages:
    @vitejs/plugin-vue: ^3.1.0 => 3.2.0
    vite: ^3.1.4 => 3.2.5
    vite-plugin-svg-sprite: ^0.3.0 => 0.3.0
gburning commented 1 year ago

The exports field still confuses me so not sure what the proper way to fix it is.

meowtec commented 1 year ago

Could you show me a minimal, reproducible example? Either a zip file or a git repository is ok.

gburning commented 1 year ago

I've tried but couldn't find the right combination of everything to still get the problem.

However, I think I have been able to track it down.

My node tsconfig extends @vue/tsconfig which in turn sets moduleResolution to 'bundler'. As the readme implies this means that TS will only resolve types through the exports field (4.7+ feature). In this case they seem to be incorrectly configured:

https://arethetypeswrong.github.io/?p=vite-plugin-svg-sprite%400.3.2

Essentially, when I try to import vite-plugin-svg-sprite it tries to resolve the .mjs file (because of "import": "./index.mjs"), but that file doesn't have a type declaration.

Fortunately, it seem like it is easy to fix: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-7.html#packagejson-exports-imports-and-self-referencing

Exactly how you fix it depends on how you wish to have your package structured I suppose, but the quickest option seems to be to add a types field to the . under exports field:

  "exports": {
    ".": {
      "types": "./lib/index.d.ts",
      "import": "./index.mjs",
      "require": "./lib/index.js"
    },
    "./runtime": "./es/runtime.js"
  }

I think this might technically be a bit of a workaround (see TS docs) but it is probably the easiest quick fix.

gburning commented 1 year ago

The more long-term approach is probably to update the typescript version used in this project

meowtec commented 1 year ago

@gburning The export way has been updated, now it is esmodule-first. Please try v0.4.0.

gburning commented 1 year ago

Thanks! It looks to be working as expected. :)