gpt4 book ai didi

node.js - Webpack渲染: "window is not defined"

转载 作者:太空宇宙 更新时间:2023-11-03 22:27:33 24 4
gpt4 key购买 nike

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

当我包含组件时

import Sound from 'react-sound';

并尝试启动服务器,我在 webpack 服务器渲染中遇到“窗口未定义” 错误。

但是如果我评论这一行并启动服务器,一切都会好起来的。之后,我可以取消注释此行,组件将可以工作,因为当服务器运行时,更改不会触发服务器渲染(仅前端渲染)。

如果我尝试

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

在渲染中

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

我在前端渲染时出现 ReferenceError: Sound is not Define 错误(在 webpack 之后)。

更新:

如果我尝试(var,而不是const)

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

我在前端渲染时遇到 TypeError: Cannot read property 'status' of undefined 错误。

最佳答案

似乎您无法在浏览器环境之外使用react-sound。

解决方案可以如下:

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>
)
}

关于node.js - Webpack渲染: "window is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43612358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com