自定义NPM包导出TS接口报错:是否缺失TS配置或构建步骤?
问题排查与解决方案
1. 类型声明文件配置问题
- 检查
IType.ts的导出语法:必须使用具名导出,示例:export interface IType { // 你的类型定义内容 } - 确保
index.d.ts正确导出IType,路径需匹配实际文件结构:export { IType } from './IType'; - 验证
tsconfig.json核心配置:- 开启
declaration: true,确保TypeScript生成类型声明文件 - 设置
outDir: "./dist",让构建产物统一输出到dist目录 include字段覆盖src下所有文件:"include": ["src/**/*"]
- 开启
2. 构建流程与package.json配置缺失
- 在package.json中添加build脚本,确保执行构建后生成dist目录:
执行"scripts": { "build": "tsc" }npm run build后,检查dist目录下是否存在index.js、index.d.ts、IType.d.ts文件。 - 配置package.json的入口字段,让TypeScript和Node能正确识别包的入口:
注意:"main": "./dist/index.js", "types": "./dist/index.d.ts"types字段必须指向构建后的类型入口文件,不能直接指向src下的文件。
3. 导入方式与缓存问题
- 在React项目中导入时,直接使用包名导入,不要写相对路径:
import { IType } from 'Custom-NPM-Package'; - 如果是本地开发用
npm link链接的包,执行npx tsc --clearCache清除TypeScript缓存,然后重启React项目的开发服务。
示例配置参考
tsconfig.json
{ "compilerOptions": { "target": "ES6", "module": "ESNext", "declaration": true, "outDir": "./dist", "strict": true, "esModuleInterop": true, "skipLibCheck": true }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"] }
package.json(关键字段)
{ "name": "Custom-NPM-Package", "version": "1.0.0", "main": "./dist/index.js", "types": "./dist/index.d.ts", "scripts": { "build": "tsc", "prepublishOnly": "npm run build" }, "devDependencies": { "typescript": "^5.0.0" } }
内容的提问来源于stack exchange,提问作者KA-Yasso
相关产品推荐
相关产品推荐

