TypeScript 5.0.2库中同时导出函数与类型的实现方案
TypeScript类库同时导出函数与类型的现代解决方案
一、先排查核心导出问题
- 确保
src/types下的.d.ts文件已显式导出类型:比如src/types/a.d.ts里必须写export type FooFunction = (...args: any[]) => void;,不能只定义类型不导出 - 检查
a.ts/b.ts中的类型导出语句路径是否正确,比如export type * from './types/a'的相对路径是否匹配文件结构
二、优化tsconfig.json配置(适配现代模块系统)
使用TypeScript 5.x的现代配置,确保声明文件正确生成:
{ "compilerOptions": { "target": "ES2020", // 适配多数运行环境 "module": "NodeNext", "moduleResolution": "NodeNext", // 对齐Node.js模块解析逻辑 "declaration": true, // 生成.d.ts文件 "declarationMap": true, // 生成类型映射,方便调试 "outDir": "./dist", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"], // 确保包含所有src下的文件(包括types目录) "exclude": ["node_modules", "dist"] }
三、完善package.json的包导出配置
添加exports字段(现代包规范优先识别),避免类型与代码路径不匹配:
{ "name": "my-library", "version": "1.0.0", "type": "module", // 启用ESM模式,若需兼容CommonJS可调整为CommonJS "main": "./dist/index.js", "types": "./dist/index.d.ts", "exports": { ".": { "import": "./dist/index.js", "require": "./dist/index.js", "types": "./dist/index.d.ts" } }, "scripts": { "build": "tsc" }, "devDependencies": { "typescript": "^5.0.2" } }
exports字段会告诉包管理器和TypeScript,无论用import还是require,都能正确找到代码和对应的类型文件。
四、简化导出链路(扁平导出模式)
直接在根入口src/index.ts统一导出函数和类型,避免中间文件中转可能的遗漏:
// src/index.ts // 导出工具函数 export * from './a'; export * from './b'; // 导出公共类型 export type * from './types/a'; export type * from './types/b';
验证步骤
- 执行
npm run build构建项目 - 检查
dist/index.d.ts文件,确认FooFunction等类型已被包含在导出列表中 - 在外部项目中通过
npm link ../my-library(或直接安装本地包)测试,确认import { foo, FooFunction } from 'my-library'能同时获取函数和类型
内容的提问来源于stack exchange,提问作者devleo
相关产品推荐
相关产品推荐

