【问题标题】:How to use Peer.js in Next.js with TypeScript?如何使用 TypeScript 在 Next.js 中使用 Peer.js?
【发布时间】:2023-01-24 05:43:53
【问题描述】:

Next.js 也在服务器端运行,因此 Peer.js 在使用 Next.js 时会引发错误。这里有人说:https://stackoverflow.com/a/66292100/239219

这可能是因为 peer js 在导入期间执行了一些副作用。

他提出这个:

useEffect(() => {
  import('peerjs').then(({ default: Peer }) => {
    // Do your stuff here
  });
}, [])

但是我需要 DataConnection 来使用 Typescript,并将其分配给 useState。你会举个例子吗?

这是我放在一起的,但是 Typescript 会引发错误:

    useEffect(() => {
        import('peerjs').then(({ default: Peer, DataConnection }) => {
            const peer = new Peer(localStorage.token)

            peer.on('connection', (conn: DataConnection) => {
                console.log('Connected to peer:', conn)

                conn.on('data', (data) => {
                    console.log('Received data:', data)
                })
            })

            return () => {
                peer.destroy()
            }
        })
    }, [])

like: 'DataConnection' 指的是一个值,但在这里用作类型。您指的是“typeof DataConnection”吗?

【问题讨论】:

    标签: javascript typescript next.js peerjs


    【解决方案1】:

    您可以在文件顶部使用 type-only import(在 3.8 版中引入):

    import type { DataConnection } from "peerjs";
    

    此导入将在输出中删除,因此请放心,这不会“提前”导入它。

    【讨论】:

      猜你喜欢
      • 2021-09-21
      • 2019-12-13
      • 2022-10-14
      • 2018-09-30
      • 2022-01-26
      • 1970-01-01
      • 2021-03-23
      • 2021-05-19
      • 2020-01-29
      相关资源
      最近更新 更多