When I run npm build using React Vite SSR plugin, I get the following error after the build:
/<path>/node_modules/enquire.js/src/MediaQueryDispatch.js:14
if(!window.matchMedia) {
^
ReferenceError: window is not defined
at new MediaQueryDispatch (/<path>/node_modules/enquire.js/src/MediaQueryDispatch.js:14:5)
at Object.<anonymous> (/<path>/node_modules/enquire.js/src/index.js:2:18)
I am sure it is coming from react-slick library because when I comment it out it works. How to fix this?
I learned that the issue is some libraries such as react-slick, at the time of this writing, does not support server-side rendering (SSR). The library expects the window object to be available but this object does not exist in a server-side rendered environment.
So the solution is to import the library only on the client-side (when the window object becomes available). Doing the below worked for me:
Then make sure to use it after it is available like this:
Additionally, adding noExternal to vite.config file helps in resolving libraries having invalid code: