【问题标题】:Next.js (React) + Phaser: ReferenceError: navigator is not definedNext.js (React) + Phaser: ReferenceError: navigator is not defined
【发布时间】:2021-09-14 11:56:13
【问题描述】:

我正在尝试使用 phaser 和 ion-phaser/react 在 Next.js 应用程序中构建包含游戏的页面。这是我的pages/game.js(使用这里的 React 示例https://github.com/proyecto26/ion-phaser):

import React, { Component } from 'react'
import Phaser from 'phaser'
import { IonPhaser } from '@ion-phaser/react'

class App extends Component {
  state = {
    initialize: false,
    game: {
      width: "100%",
      height: "100%",
      type: Phaser.AUTO,
      scene: {}
    }
  }
  render() {
    const { initialize, game } = this.state
    return (
      <IonPhaser game={game} initialize={initialize} />
    )
  }
}

export default App;

运行next dev 并访问该页面会出现以下错误:

ReferenceError: navigator is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
init
file:///C:/git_projects/game/node_modules/phaser/src/device/OS.js (69:14)
Object.<anonymous>
file:///C:/git_projects/game/node_modules/phaser/src/device/OS.js (186:18)
Module._compile
internal/modules/cjs/loader.js (1063:30)
Object.Module._extensions..js
internal/modules/cjs/loader.js (1092:10)
Module.load
internal/modules/cjs/loader.js (928:32)
Function.Module._load
internal/modules/cjs/loader.js (769:14)
Module.require
internal/modules/cjs/loader.js (952:19)
require
internal/modules/cjs/helpers.js (88:18)
Object.<anonymous>
file:///C:/git_projects/floam/node_modules/phaser/src/device/index.js (32:9)
Module._compile
internal/modules/cjs/loader.js (1063:30)

为什么没有定义navigator?

这些是我在package.json中的相关包版本:

"next": "^9.5.5",
"react": "^16.5.2",
"react-dom": "^16.5.2",
"phaser": "^3.55.2",
"@ion-phaser/react": "^1.3.0",

【问题讨论】:

    标签: reactjs next.js phaser-framework


    【解决方案1】:

    可能这个包不适合 SSR。似乎它在没有检查浏览器 api 的可用性的情况下调用 navigator,并且在服务器端引发错误。

    如果这个包是 React 组件,那么你可以尝试使用next/dynamic 来导入它(使用ssr: false 将它从 SSR 中排除):

    import dynamic from 'next/dynamic'
    
    const Phaser = dynamic(
      () => import('@ion-phaser/react'),
      { ssr: false }
    )
    

    如果这不起作用,那么您需要使用常规的非 Next.js 动态 import() 来导入整个模块(可能在 useEffect 中)

    【讨论】:

      【解决方案2】:

      我不得不使用 useEffect,像这样:

      useEffect(async () => (window.Phaser = await import(`phaser`)), []);
      

      【讨论】:

        猜你喜欢
        • 2022-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-02
        • 2014-03-03
        • 2021-12-09
        • 1970-01-01
        相关资源
        最近更新 更多