You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vite React TS组件库index.d.ts存在但npm安装后无法被识别

解决TypeScript组件库类型声明无法解析的问题

问题描述

基于Vite、React.js和TypeScript开发的组件库发布到npm后,在新项目中执行npm install安装后出现以下警告,导致项目无法编译:

Could not find a declaration file for module 'c-forms'. 'app/node_modules/c-forms/dist/c-forms.es.js' implicitly has an 'any' type.
There are types at 'app/node_modules/c-forms/dist/index.d.ts', but this result could not be resolved when respecting package.json "exports". The 'c-forms' library may need to update its package.json or typings.

原因分析

当package.json配置了exports字段时,TypeScript会优先依据exports的规则解析模块,而原配置中未在主入口的exports节点内指定types字段,导致TypeScript无法将主入口文件与对应的声明文件关联起来。

解决方案

1. 修正package.json的exports配置

在主入口的import和require配置下添加types字段,同时移除单独的./dist/index.d.ts导出项,修改后的exports如下:

"exports": {
  ".": {
    "import": "./dist/c-forms.es.js",
    "require": "./dist/c-forms.umd.js",
    "types": "./dist/index.d.ts"
  },
  "./dist/style.css": "./dist/style.css"
},

保留顶层的types字段作为兼容:

"types": "./dist/index.d.ts",

2. 调整tsconfig.json配置

移除include数组中的dist/index.d.ts,因为dist是构建产物,无需在源码编译阶段包含:

"include": ["src"],

3. 确认Vite插件配置

保持vite-plugin-dts的现有配置,确保它能正确生成类型文件:

dts({
  insertTypesEntry: true,
  rollupTypes: true,
}),

insertTypesEntry: true会自动生成类型入口,无需额外手动配置。

4. 重新构建并发布

执行构建命令确认产物正确:

npm run build

检查dist目录下的index.d.ts是否包含所有组件的类型声明,然后重新发布到npm:

npm publish

完成以上步骤后,在新项目中重新安装组件库,类型声明即可正常被TypeScript识别,编译警告将消除。

内容的提问来源于stack exchange,提问作者Nie Selam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 05:35:55