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

React+Vite集成simple-peer实现WebRTC遇两类问题求助

使用simple-peer + React + Vite开发WebRTC通话应用的问题解决

问题1:Module "util" 外部化警告

问题描述

simple-peer.js?v=76ad0f10:2833 Module "util" has been externalized for browser compatibility. Cannot access "util.inspect" in client code.

解决方法

Vite默认会将Node.js核心模块标记为外部依赖,而simple-peer依赖了Node的util模块。通过vite-plugin-node-polyfills插件为浏览器环境提供兼容:

  1. 安装插件:
npm install vite-plugin-node-polyfills --save-dev
  1. 修改vite.config.js配置:
import { nodePolyfills } from 'vite-plugin-node-polyfills'
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [
    react(),
    nodePolyfills({
      include: ['util']
    })
  ]
})

问题2:安全随机数生成不支持错误

问题描述

执行const peer= new Peer({initiator:false,trickle:false,stream:stream})时触发:

Uncaught Error: Secure random number generation is not supported by this browser. Use Chrome, Firefox or Internet Explorer 11

解决方法

这个错误源于simple-peer依赖的crypto模块在浏览器环境中缺失,同时WebRTC要求运行在安全上下文:

  1. 扩展插件配置,添加crypto模块的兼容:
nodePolyfills({
  include: ['util', 'crypto']
})
  1. 确保运行环境满足:
    • 本地开发使用localhost(Chrome默认视为安全上下文)
    • 生产环境必须部署在HTTPS协议下
    • 避免在浏览器隐身模式下测试(部分隐私模式会限制加密API)

如果不想使用插件,也可以单独安装crypto-browserify并配置别名:

  1. 安装依赖:
npm install crypto-browserify --save
  1. 修改vite.config.js:
export default defineConfig({
  resolve: {
    alias: {
      'crypto': 'crypto-browserify'
    }
  },
  plugins: [react()]
})

额外检查

确认你的媒体流stream已通过navigator.mediaDevices.getUserMedia正确获取,无效的流也可能间接引发异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 21:45:03