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

如何在Next.js(TypeScript)中使用Peer.js并处理DataConnection类型问题

Next.js + Peer.js + TypeScript 正确实现方案

问题根源

Next.js的SSR环境下直接初始化Peer.js会触发浏览器专属API(如window)未定义的错误;而TypeScript中报错的核心是:动态导入的Peer模块里的DataConnection是构造函数(运行时值),不能直接当作类型使用,必须单独导入类型定义。

解决步骤

  1. 先安装依赖:
npm install peer @types/peer
  1. 组件内完整实现代码:
import { useState, useEffect } from 'react';
// 用import type单独导入类型,明确区分运行时值与类型定义
import type { Peer, DataConnection } from 'peerjs';

export default function PeerConnectionComponent() {
  // 明确指定状态的类型为DataConnection或null
  const [activeConnection, setActiveConnection] = useState<DataConnection | null>(null);
  const [peer, setPeer] = useState<Peer | null>(null);

  useEffect(() => {
    // 动态导入Peer.js,确保代码仅在浏览器客户端执行
    const initPeerInstance = async () => {
      const { default: Peer } = await import('peerjs');
      const newPeer = new Peer('your-unique-peer-id');

      newPeer.on('open', (id) => {
        console.log('当前Peer ID:', id);
      });

      // 监听外部发起的连接请求
      newPeer.on('connection', (conn) => {
        conn.on('data', (data) => {
          console.log('收到数据:', data);
        });
        setActiveConnection(conn);
      });

      setPeer(newPeer);
    };

    initPeerInstance();

    // 组件卸载时清理资源
    return () => {
      peer?.destroy();
      activeConnection?.close();
    };
  }, []);

  // 主动发起连接的示例函数
  const initActiveConnection = (targetPeerId: string) => {
    if (!peer) return;
    const newConn = peer.connect(targetPeerId);
    newConn.on('open', () => {
      newConn.send('来自Next.js的消息!');
      setActiveConnection(newConn);
    });
  };

  return (
    <div>
      <button onClick={() => initActiveConnection('目标Peer的ID')}>发起连接</button>
    </div>
  );
}

核心要点

  • 用import type导入Peer和DataConnection,让TypeScript明确识别这是类型而非运行时变量,解决类型误用的报错。
  • 借助useEffect动态导入peerjs模块,规避Next.js SSR环境下的浏览器API兼容性问题。
  • 状态定义时显式指定DataConnection | null类型,让TypeScript正确推导状态的类型范围。

内容的提问来源于stack exchange,提问作者János

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 05:05:14