繁体   English   中英

ReferenceError: 窗口未在 React 中定义

[英]ReferenceError: window is not defined in React

我为我的应用程序安装了“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”。 但同样的错误正在发生。

此库与 SSR(服务器端渲染)不兼容。 我猜你正试图用 webpack 做到这一点。

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

我想这可能不会引发任何错误,请记住您必须在导入库之前声明这一点。

我对react-speech包一无所知。 但是我在尝试使用 webpack 为浏览器捆绑我的一个模块时遇到了类似的事情(捆绑进程在node运行,并且window在该context未定义)。 这是我使用的:

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(...)

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

添加这一行let window = window || global.window let window = window || global.window这在global.window窗口时给出窗口global.window的值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM