React中出现了ReferenceError: window is not defined错误

9

我安装了"react-speech"包来为我的应用程序构建文本转语音功能。但是在导入包时,我遇到了以下错误。我已经进行了足够的谷歌搜索以解决此问题,但无法解决。非常感谢任何帮助。

错误:

ReferenceError: window is not defined

    at new SpeakTTS (/Users/moharja/Project/React-master/node_modules/speak-tts/lib/speak-tts.js:22:48)

    at Object.<anonymous> (/Users/moharja/Project/React-master/src/components/Judgement/Landing/RightBar/Top/top.component.jsx:24:16)

    at Module._compile (internal/modules/cjs/loader.js:1201:30)

    at Module._compile (/Users/moharja/Project/React-master/node_modules/pirates/lib/index.js:99:24)

    at Module._extensions..js (internal/modules/cjs/loader.js:1221:10)

    at Object.newLoader [as .jsx] (/Users/moharja/Project/React-master/node_modules/pirates/lib/index.js:104:7)

    at Module.load (internal/modules/cjs/loader.js:1050:32)

    at Function.Module._load (internal/modules/cjs/loader.js:938:14)

    at Module.require (internal/modules/cjs/loader.js:1090:19)

    at require (internal/modules/cjs/helpers.js:75:18)

npm ERR! code ELIFECYCLE

npm ERR! errno 1

npm ERR! lm-suite-react@0.1.0 start: `rimraf build && webpack --mode production --progress --profile --color && node index.js`

npm ERR! Exit status 1

npm ERR!

npm ERR! Failed at the lm-suite-react@0.1.0 start script.

npm ERR! This is probably not a problem with npm. There is likely additional logging output above.



npm ERR! A complete log of this run can be found in:

npm ERR!     /Users/moharja/.npm/_logs/2020-10-19T17_30_09_085Z-debug.log `

注意:我也尝试使用不同的包代替“react-speech”。但是仍然出现相同的错误。

2
如果你在Node中运行这个程序,是的,在node.js中没有window对象。我假设SpeakTTS是一个浏览器组件,所以它不能在node.js中运行。 - Keith
你的启动脚本是什么? - Yilmaz
3个回答

4

此库不支持SSR(服务器端渲染)。 我猜你正在尝试使用webpack进行SSR。

if (typeof window === 'undefined') {
  global.window = {}
}

我猜这可能不会抛出任何错误,在导入库之前你必须先声明它。


1
抛出以下错误:"试图分配给常量或只读变量"。 - Ariel Mirra

1

我对react-speech包一无所知。但是在尝试使用webpack将我的一个模块打包到浏览器时(打包过程在node上运行,而context中的window未定义),我遇到了类似的问题。

这是我使用的代码:

let win
try {
  win = window
} catch (error) {
  // suppress the Reference error and assign an empty object to win
  // this should not be reachable in actual browser as window 
  // will be defined in that context.

  win = {} 
} 

我们这样做只是为了让Webpack在构建模块时不抛出错误。

... 
// replace window with win

// window.fetch(...)
win.fetch(...)

由于您正在尝试使用由他人维护的库,您可以尝试自己构建它,或者您可以为包维护者提出问题。


0

我想强调,在构建应用程序后,在 docusaurus 中遇到这个问题是相当常见的。为了解决这个问题,您可以通过在 <Root> 组件内使用条件 if (typeof window !== "undefined") 来解决。该组件被渲染在 React 树的顶部,确保在任何子组件中使用 window 时不会遇到任何问题。

如果您的应用程序中不存在 Root 组件,请在 src/theme 下创建它。

src/theme/Root.js

import React from "react";
export default function Root({ children }) {
  if (typeof window !== "undefined") {
    return (
      <>
        {children}
      </>
    );
  }
  return null;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接