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

自定义TS库导入报错:找不到模块声明文件,如何修改构建配置?

解决自定义TypeScript库导入时的类型声明缺失问题

我编写了一个自定义TypeScript(TS)库,但将其导入其他项目时出现如下报错:

Could not find a declaration file for module '@org/navigation-cards-panther-test'. '../node_modules/@org/navigation-cards-panther-test/index.js' implicitly has an 'any' type.
Try npm i --save-dev @types/org__navigation-cards-panther-test if it exists or add a new declaration (.d.ts) file containing declare module '@org/navigation-cards-panther-test';

我的tsconfig.json配置如下:

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "commonjs",
    "lib": [
      "es2016",
      "es2017.object",
      "es2017.string"
    ],
    "declaration": true,
    "baseUrl": "src/",
    "rootDir": "./src",
    "outDir": "./dist",
    "declarationDir": "./dist/types",
    "moduleResolution": "node",
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": false,
    "inlineSourceMap": true,
    "inlineSources": true,
    "experimentalDecorators": true,
    "esModuleInterop": true,                 
    "forceConsistentCasingInFileNames": true,
    "strictPropertyInitialization": false,
    "skipLibCheck": true,

    "typeRoots": [
      "./node_modules/@types"
    ]
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "build",
    "node_modules"
  ]
}

我的项目目录结构:

.
├── README.md
├── package-lock.json
├── package.json
├── src
│   └── NavigationCardsPanther
│       └── index.ts
└── tsconfig.json

解决方法

要让其他TS项目识别到你的库的类型声明,需要做以下几个关键调整:

1. 配置package.json的类型入口

在库的package.json中添加types字段,明确指向编译生成的类型声明文件路径。根据你的配置,类型文件会生成在dist/types/NavigationCardsPanther/index.d.ts,所以配置如下:

{
  "main": "./dist/NavigationCardsPanther/index.js", // 确保指向编译后的JS入口
  "types": "./dist/types/NavigationCardsPanther/index.d.ts"
}

2. 确认类型文件已正确生成

运行tsc编译后,检查dist/types目录下是否生成了对应的.d.ts文件。如果没生成,核对以下配置:

  • declaration已设为true(你的配置没问题)
  • include字段覆盖了所有需要生成类型的源文件(src/**/*符合要求)
  • rootDir正确指向src目录(你的配置已设为./src)

3. 可选:调整类型文件输出结构

如果希望类型文件和编译后的JS文件同目录,可以删除tsconfig.json中的declarationDir配置,此时.d.ts文件会自动生成在outDir对应的路径下。这种情况下package.json的types字段可以改为:

"types": "./dist/NavigationCardsPanther/index.d.ts"

更符合Node模块的默认查找逻辑。

4. 确保发布时包含类型文件

在package.json的files字段中加入dist目录,保证发布npm包时,编译后的JS和类型文件会被一同打包:

{
  "files": [
    "dist"
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 23:15:10