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

自定义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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:35:00