Wolox / react-chat-widget

Awesome chat widget for your React App
MIT License
1.46k stars 459 forks source link

Not working on server side rendering #153

Open chyke007 opened 4 years ago

chyke007 commented 4 years ago

Is it possible to make this work on server side rendering. I am using Gatsby and it happens to work fine on development but fails on production with the error message "window" is not available during server side rendering.

Is there any work around for this. Thanks.

chyke007 commented 4 years ago

I solved this issue by adding these two dependencies to my package.json

  1. react-dynamic-import
  2. @loadable/component

And then importing the component I had my chat code into my display component.

import ReactDynamicImport from "react-dynamic-import" import Chat from './chat';

Then wrapped the chat component using the dynamic import

const loader = () => import('./chat'); const RealComponent = ReactDynamicImport({loader});

Then I rendered it.

  <RealComponent />

Hope this helps.

felpsio commented 4 years ago

I forked and tried to adapt the code to work server side. But got suck on a problem that I think is related to webpack.

I search the project for all the window references and added a verification to check if it's undefined. But even after adding this condition to all the places the file generated still have a window reference that I couldn't find the origin:

!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):"object"==typeof exports?exports["react-chat-widget"]=t(require("React"),require("ReactDOM")):e["react-chat-widget"]=t(e[void 0],e[void 0])}(window,function(e,t){return function(e){var t={};function r(n){if(t[n])return t[n].exports (...)

Since is in the beginning of the final file I think that one of the steps inside webpack may be generating this reference. If I change the part on the final output the code works fine with the build from my project

Any idea where this reference may be coming from? I would be happy to finish the adaptation and make it work on Gatsby

chyke007 commented 4 years ago

I have no idea yet where this window reference is imported into the code, I had similar issue but after a long time debugging had to look for a walk around. It is really a great idea that you have picked this up, I would try and search more about this issue in my free time to see if I could also figure it out.

felpsio commented 4 years ago

@chyke007 I checked again and I think I figured out

It comes from libraryTarget: 'umd'

If I change umd to amd on webpack.config.prod.js the window is removed. Do you think it may generate any dangerous side effect? If not we may try a branch with this change