Webpack渲染:“窗口没有定义”

我使用MERN – https://github.com/Hashnode/mern-starter(react,redux,webpack,nodejs,express )和组件react-sound – https://github.com/leoasis/react-sound

当我包含组件

import Sound from 'react-sound'; 

并尝试启动服务器,我有"window is not defined"错误从webpack服务器渲染。

但是,如果我评论这条线并启动服务器,一切都会好起来的。 之后,我可以取消注释这一行,组件将工作,因为当服务器正在运行,更改不会触发服务器呈现(只有正面呈现)。

如果我尝试

 if (typeof window !== 'undefined') { const Sound = require('react-sound'); } 

并在渲染

 render() { return ( <div> <Sound playStatus={Sound.status.STOPPED} url="" /> </div> ); } 

我有ReferenceError: Sound is not defined在前面渲染错误(在webpack之后)。

更新:

如果我尝试( var ,不是const

 if (typeof window !== 'undefined') { var Sound = require('react-sound'); } 

我有TypeError: Cannot read property 'status' of undefined正面呈现TypeError: Cannot read property 'status' of undefined错误的TypeError: Cannot read property 'status' of undefined

似乎你不能在浏览器环境之外使用反应声音。

解决scheme可以如下:

 let SoundEl; if (typeof window !== 'undefined') { import Sound from 'react-sound'; SoundEl = <Sound playStatus={Sound.status.STOPPED} url="" /> } else { SoundEl = <div></div> } 

 render() { return ( <div> {SoundEl} </div> ) }