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

Telegram Bot Web App开发报错:Telegram/WebApp变量未解析

问题:Telegram Web App调用时出现「Unresolved variable」错误

我正在为Telegram Bot开发Web App,已按照官方文档要求在Create React App的public/index.html中引入telegram-web-app.js脚本,相关代码如下:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <script src="https://telegram.org/js/telegram-web-app.js"></script>
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

尝试通过const tg = window.Telegram.WebApp;调用Telegram WebApp时,出现报错:Unresolved variable Telegram、Unresolved variable WebApp,请问该如何解决?


解决方案

1. 补充类型声明(适配TypeScript/IDE智能提示)

如果是TypeScript项目,直接安装官方类型包:

npm install @types/telegram-web-app --save-dev

如果是JavaScript项目,可在src目录下创建global.d.ts文件,添加全局变量声明:

declare global {
  interface Window {
    Telegram: {
      WebApp: any;
    };
  }
}
export {};

或者在使用Telegram的文件顶部添加注释:

/* global Telegram */

2. 确保脚本加载完成后再调用

即使脚本放在head中,也可能出现React代码先执行的情况,建议在组件中通过useEffect判断后再调用:

import { useEffect } from 'react';

function App() {
  useEffect(() => {
    // 先检查Telegram对象是否存在
    if (window.Telegram?.WebApp) {
      const tg = window.Telegram.WebApp;
      // 执行WebApp初始化操作
      tg.ready();
    }
  }, []);

  return <div id="app"></div>;
}

export default App;

3. 配置ESLint忽略全局变量

如果是ESLint报的错,在.eslintrc.json中添加全局变量配置:

{
  "globals": {
    "Telegram": "readonly"
  }
}

尽量避免用/* eslint-disable no-undef */全局禁用的方式,保持规则精准性。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 13:15:26