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

TypeScript中跨模块共享mwn机器人实例及编译配置问题求助

解决方案

一、修复全局变量类型错误

你之前的类型声明核心错误在于:mwn.init()返回的是mwn.Bot实例,而非mwn模块本身,同时全局对象的类型扩展需要正确关联。调整步骤如下:

1. 修改src/types/global.d.ts

import type { Bot } from 'mwn';

declare global {
  var mw: Bot | undefined;
}

// 必须导出空对象确保文件被识别为模块
export {};
  • 用type导入避免引入实际模块代码
  • 标记mw为undefined类型,适配异步初始化的时序问题
  • 末尾添加export {},让TypeScript识别这是模块文件,否则全局声明不生效

2. 修正bot.ts中的全局赋值

使用标准的globalThis替代global,同时确保实例类型匹配:

import { mwn } from 'mwn';
import { my } from './my';

(async () => {
  globalThis.mw = await mwn.init(my.userinfo);
  // 初始化完成后再加载依赖实例的模块,避免未定义问题
  await import('./module-that-uses-mw');
})();

二、解决ts-node/nodemon的模块兼容问题

核心是让TypeScript编译输出和Node.js运行环境统一使用CommonJS,避免ES模块与CommonJS的冲突:

1. 配置tsconfig.json

确保关键参数如下:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}
  • module: "CommonJS":让TS编译产物与Node.js默认模块规范兼容
  • esModuleInterop: true:解决ES模块导入CommonJS模块的语法兼容问题

2. 调整package.json

不要设置"type": "module",添加运行脚本:

{
  "scripts": {
    "start": "ts-node src/bot.ts",
    "dev": "nodemon --watch src --exec ts-node src/bot.ts",
    "build": "tsc"
  },
  "devDependencies": {
    "ts-node": "^10.9.1",
    "typescript": "^5.2.2",
    "nodemon": "^3.0.1"
  }
}

3. 验证运行

执行npm run dev,nodemon会监听src目录变动,通过ts-node直接运行TS文件,不会再出现模块或文件扩展名错误。

额外建议:替代全局变量的优雅方案

全局变量容易引发时序和类型问题,推荐用单例模式共享实例:

  1. 创建src/singleton/bot.ts:
import { mwn, Bot } from 'mwn';
import { my } from '../my';

let botInstance: Bot | undefined;

export async function getBot(): Promise<Bot> {
  if (!botInstance) {
    botInstance = await mwn.init(my.userinfo);
  }
  return botInstance;
}
  1. 在其他模块中使用:
import { getBot } from './singleton/bot';

async function editPage() {
  const bot = await getBot();
  await bot.edit('Page title', () => ({ text: 'new content' }));
}

这种方式更符合TypeScript的类型规范,也避免了全局变量的潜在风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:35:20