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

Storybook设计系统声明文件缺失:TypeScript类型解析异常求助

解决TypeScript模块声明解析错误(TS7016)

问题场景

构建基于Storybook、ViteJS、React和TypeScript的设计系统包后,关联到项目时出现如下TypeScript错误:

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

原因分析

当package.json中配置了exports字段时,TypeScript会优先遵循exports规则解析模块,忽略根目录的types字段。当前exports仅指定了CommonJS和ES模块的入口文件,未对应声明类型文件路径,导致TypeScript无法匹配到正确的类型声明。

解决方案

1. 更新package.json的exports配置

在exports的根路径配置中添加types字段,指向生成的类型声明文件:

"exports": {
  ".": {
    "require": "./dist/mypackage.cjs",
    "import": "./dist/mypackage.es.js",
    "types": "./dist/index.d.ts"
  }
}

此配置让TypeScript在处理不同模块导入方式时,能明确找到对应的类型声明文件。

2. 确认类型生成配置

  • 检查Vite配置中的vite-plugin-dts插件,确保include覆盖所有需要生成类型的源码目录(当前配置include: ['src']符合要求)。
  • 确认tsconfig.json中declaration设为true,vite-plugin-dts会基于此配置将类型文件生成到dist目录。

3. 重新构建并关联包

执行构建命令重新生成包文件:

npm run build

之后在目标项目中重新安装或关联该包,必要时清除项目缓存:

rm -rf node_modules && npm install
# 若使用npm link
npm unlink mypackage && npm link mypackage

4. 验证类型文件存在

确认dist目录下已生成index.d.ts文件,确保构建过程中类型文件正确输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 11:22:26