问题描述
您好我正在尝试在reactJS项目中使用react-rte。我有服务器端渲染,每次我想使用这个包我得到:
Hi I'm trying to use react-rte in my reactJS project. I have server side rendering and every time I want to use this package I get:
return /msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase());
^
ReferenceError: window is not defined
我想问题可能是使用isomorphic-tools但我不知道如何将包导入到已经定义窗口的客户端。
I guess the problem might be with isomorphic-tools but I don't know how to defer importing package to the client where window is going to be defined already.
推荐答案
如果你正在进行服务器端渲染,那么全局窗口对象很可能是未定义的,因为这只是客户端会理解的东西。
If you're doing server side rendering, there's a good chance that the global window object is going to be undefined because that is only something the client will understand.
我在这种情况下使用了一种解决方法。这就是我的webpack插件所具有的:
There is a workaround that I am using in this case. This is what I have for my webpack plugin:
new webpack.DefinePlugin({
'process.env.NODE_ENV': isDevelopment ? '"development"' : '"production"',
'process.env.BROWSER': JSON.stringify(true),
__DEV__: isDevelopment
}),
所以我使用 process.env.BROWSER
对我有利,因为它将被定义为 undefined
如果它是服务器端,如果客户端完成渲染,它将是 true
。
So I use process.env.BROWSER
to my advantage because it will be defined as undefined
if it is server side, and it will be true
if the client side is done rendering.
由于当服务器端没有窗口对象时,一切都停止工作,我们可以添加:
Since everything just stops working when there isn't a window object on the server side we can add this:
const mySpecialWindowFunction = () => {
/* START HACK */
if (!process.env.BROWSER) {
global.window = {}; // Temporarily define window for server-side
}
/* END HACK */
return /msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase());
};
这样,你的控制台不会尖叫你并且不会停止服务器端渲染,你现在可以继续光荣的一天!虽然我不得不承认这有点 Hacky ,但它完成了工作,因为我们要做的就是让服务器端渲染出初始的DOM字符串然后让客户端接受结束。
That way, your console won't scream at you and doesn't stop the server side rendering, to which you can now carry on with your glorious day! Although I have to admit that this is a bit Hacky, but it gets the job done because all we want to do is let the server side render out the initial DOM string and then let the client-side take over.
这篇关于反应JS服务器端问题 - 找不到窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!