SuperAPI AI 工具集

cometchat-react-v7-patterns

前端与建站

查看项目

更新于 10-21 20:28

技能介绍

用途

本技能面向需要把 CometChat React v7 UI Kit(@cometchat/chat-uikit-react@7)接入具体 React 工具链的开发者,或需要排查环境变量、路由、SSR 相关问题的场景。它假定使用者已掌握配套技能 cometchat-react-v7-core(安装、Provider、init→login→render),本技能只处理“框架接线”这一层差异。

主要能力

按工具链给出接线要点(delta):

  • Vite:环境变量放在 .env,使用 VITE_ 前缀,通过 import.meta.env.VITE_COMETCHAT_* 读取;init/login 放在应用启动 effect 中;CometChatProvider 挂在聊天路由之上。
  • Create React App:环境变量使用 REACT_APP_ 前缀,通过 process.env.REACT_APP_* 读取。
  • Next.js:该 Kit 仅限客户端使用,init/login 与 CometChatProvider 需放在 Client Component("use client")中;环境变量放在 .env.local,使用 NEXT_PUBLIC_* 前缀;需保护仅浏览器可用的代码,避免在 SSR 期间执行(App Router 与 Pages Router 均适用)。
  • React Router / Remix:分两种模式。v6 library 模式(在 Vite/CRA 应用内路由、无 SSR)按 Vite 方式接线,使用 VITE_ 环境变量;v7 framework 模式(SSR,Remix 的继任者,旧 @remix-run/react 应用映射到此)具有类似 Next 的 SSR 注意事项,需让聊天仅客户端渲染(client guard / clientLoader / <ClientOnly>),使用 VITE_ 环境变量,Provider 放在路由 outlet 之上。
  • Astro:该 Kit 作为 React island 挂载,使用 client:only="react"(绝不可 SSR);环境变量使用 PUBLIC_ 前缀(import.meta.env.PUBLIC_COMETCHAT_*);由一个 island 负责 init/login + provider + 聊天。

此外强调:CometChatProvider 应保持在稳定的祖先层级,使 init/login 在导航切换后依然存活。

使用方式

本技能不引入新包,前置条件由 cometchat-react-v7-core 覆盖。完整的分框架接线配方需通过 cometchat-react-v7-core/references/docs-map.md 获取文档集成页(integration-react、integration-nextjs、integration-react-router、integration-astro,以及 next-* / react-router-* / astro-* 布局配方);本技能只内置上述差异点。

适用场景

  • 在 Vite、CRA、Next.js、React Router(含 Remix)、Astro 中集成该 UI Kit。
  • 排查环境变量读取为 undefined、SSR 报错、路由切换后聊天状态丢失等问题。

限制与注意事项

框架坑(已内置):

  • SSR 框架(Next.js、React Router v7 framework 模式、Astro)在服务端渲染该 Kit 时会出现 window is not defined / hydration 错误,需让聊天仅客户端渲染(Next 用 "use client";Astro 用 client:only="react";React Router v7 用 client guard / clientLoader),并把 init 推迟到 useEffect/浏览器端。
  • Astro 若使用 client:load/client:visible(会先 SSR 组件)而非 client:only="react",会导致服务端渲染崩溃。
  • 环境变量前缀与工具链不匹配(Vite/React-Router 用 VITE_、CRA 用 REACT_APP_、Next 用 NEXT_PUBLIC_、Astro 用 PUBLIC_)会导致运行时取值为 undefined。
  • 在多个入口重复导入 UI Kit CSS(应在根处只导入一次)。
  • 生产环境将 auth key 下发到客户端——应使用服务端 token 交换(见 RULES.md)。
  • 版本冲突:若安装的是 v6,按 core 的说明 STOP。

Vite 的 brownfield 注意点(AUDIT-037/066):若未接入 vite/client 类型,import.meta.env 将无类型,严格 TS 构建会报 TS2339: Property 'env' does not exist on ImportMeta。不同 Vite 版本的脚手架接入方式不同——较旧版本提供 src/vite-env.d.ts(/// <reference types="vite/client" />),较新版本(Vite 8+)把 "vite/client" 放入 tsconfig.app.json 的 types 数组。不要假设其中任一存在,应先检查,再确保引用 vite/client:在读取环境变量的文件顶部加 /// <reference types="vite/client" />(自包含,跨 Vite 版本可用),或把 "vite/client" 加入 tsconfig.app.json 的 compilerOptions.types,或创建 src/vite-env.d.ts。

验证方式

应用能在所用框架(Vite / Next / React Router / Astro)下成功构建,聊天正常渲染,且环境变量前缀正确、SSR 保护到位(按需使用 "use client" / ssr:false)。