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

如何在不同文件声明多模块?导入模块遇TS2307错误求助

解决TypeScript找不到模块'starnime/discord/webhook'的问题

我在导入类时遇到错误提示:

Cannot find module 'starnime/discord/webhook' or its corresponding type declarations.ts(2307)

即便已在typings文件夹中声明了该模块,且添加了tsconfig.json配置,问题仍未解决。我的tsconfig.json配置如下:

{
    "compilerOptions": {
        "allowUnreachableCode": false,
        "allowUnusedLabels": false,
        "exactOptionalPropertyTypes": true,
        "noFallthroughCasesInSwitch": true,
        "noImplicitOverride": true,
        "noImplicitReturns": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "strict": true,
        "useUnknownInCatchVariables": true,
        "noUncheckedIndexedAccess": true,
        "outDir": "dist",
        "allowJs": true,
        "target": "es2017",
        "noImplicitAny": true
    },
    "include": [
        "./**/*"
    ],
    "exclude": [
        "node_modules"
    ]
}

我期望能成功通过以下方式导入类:

const { DiscordEmbed, DiscordWebhook } = require('starnime/discord/webhook');

// rest of the code

可能的解决办法

1. 核对类型声明文件的路径与内容

  • 模块路径是starnime/discord/webhook,对应的类型声明文件必须放在typings/starnime/discord/webhook.d.ts,路径层级要完全匹配;
  • 声明文件内要正确使用declare module包裹类型定义:
declare module 'starnime/discord/webhook' {
  export class DiscordEmbed {
    // 补充类的具体类型定义
  }
  export class DiscordWebhook {
    // 补充类的具体类型定义
  }
}

2. 让TypeScript识别自定义typings文件夹

在tsconfig.json的compilerOptions里添加typeRoots字段,指定类型声明的查找目录:

"compilerOptions": {
  // 保留原有配置...
  "typeRoots": ["./typings", "./node_modules/@types"]
}

默认TypeScript只会优先找node_modules/@types,手动加入./typings能确保自定义声明被识别。

3. 确认模块实际文件存在且路径正确

确保项目中存在starnime/discord/webhook对应的.js或.ts文件,路径要和导入路径完全对应。如果是自定义模块,还可以通过以下方式优化解析:

  • 在项目根目录的package.json里添加exports字段,明确映射模块路径;
  • 确认模块所在目录被tsconfig.json的include规则覆盖(当前include: ["./**/*"]应该没问题,但可以检查是否有被exclude意外排除)。

4. 显式设置模块解析策略

因为用的是CommonJS的require导入,建议在tsconfig.json的compilerOptions里显式设置module为CommonJS,避免默认规则导致的解析问题:

"compilerOptions": {
  // 保留原有配置...
  "module": "CommonJS"
}

5. 清除缓存重启服务

TypeScript的缓存可能导致声明更新不生效,尝试:

  • 删除项目里的.tsbuildinfo文件(如果存在);
  • 重启编辑器的TypeScript语言服务(比如VS Code按Ctrl+Shift+P执行TypeScript: Restart TS Server);
  • 重新执行编译命令。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:10:30