如何为NPM包生成正确的TypeScript声明文件?
解决NPM包TypeScript声明文件生成问题
问题核心
你遇到的两种声明文件生成方式的问题根源:
- 单文件模式:
tsc的outFile生成的是模块集合声明(大量declare module块),而非包的顶层导出API,导致客户端识别为「非模块」。 - 多文件模式:缺少顶层
index.d.ts是因为源码入口的导出未被正确映射,且tsconfig配置未指定正确的输出结构。
解决方案一:多文件声明(推荐,符合TS包规范)
1. 调整tsconfig.dts.json配置
修改为如下内容,重点修正根目录、输出目录和模块配置:
{ "compilerOptions": { // 注释outFile,改用outDir生成目录结构 "outDir": "./dist/types", "declarationDir": "./dist/types", "rootDir": "./src", // 指定源码根目录,避免生成的声明带src前缀 "jsx": "react-jsx", "lib": ["dom", "dom.iterable", "es6"], "moduleResolution": "Node", "esModuleInterop": true, "baseUrl": "./", "paths": { "@/*": ["src/*"] }, "allowJs": false, // 源码是TS,无需允许JS "declaration": true, "emitDeclarationOnly": true, "declarationMap": true, "module": "ESNext", // 匹配Rollup的输出模块格式 "target": "ESNext" }, "include": [ "src/**/*", "globals.d.ts" ], "exclude": [ "src/**/*.stories.ts?(x)", "src/**/*.mock.ts?(x)", "src/**/*.test.ts?(x)", "src/app/**" ] }
2. 确保源码入口导出完整API
在src/components/index.ts中导出所有对外暴露的组件和类型:
export { AdditionalResults } from './AdditionalResults/AdditionalResults'; export type { AdditionalResultsProps, Result } from './AdditionalResults/AdditionalResults.definition'; // 其他组件/类型的导出...
3. 配置Package.json类型入口
在package.json中指定声明文件入口:
{ "main": "dist/index.js", "module": "dist/index.es.js", "types": "dist/types/components/index.d.ts" // 对应生成的声明文件路径 }
如果希望顶层index.d.ts自动生成,可在src下新增index.ts:
// src/index.ts export * from './components/index';
同时修改Rollup的input为./src/index.ts,package.json的types改为dist/types/index.d.ts。
解决方案二:单文件声明(需用第三方工具)
tsc的outFile不适用于ESM/CJS包,改用dts-bundle-generator生成正确的单文件声明:
- 安装工具:
npm install -D dts-bundle-generator - 修改
postbuild命令:"postbuild": "dts-bundle-generator src/components/index.ts -o dist/index.d.ts" - 配置
package.json:"types": "dist/index.d.ts"
验证步骤
- 执行
npm run build,检查dist目录下的声明文件结构是否符合预期。 - 在客户端项目中安装包,尝试导入组件,确认TS能正确识别类型。
- 若客户端仍报错,检查其
tsconfig.json的skipLibCheck是否为false,确保类型检查生效。
内容的提问来源于stack exchange,提问作者BenZ
相关产品推荐
相关产品推荐

