简体   繁体   中英

How to handle window object on nodejs for server-side rendering of reactjs application

I am trying to implement server-side rendering for my reactjs application. I am using webpack to build reactjs application, enhanced-resolve to handle importing of jsx files in nodejs.

My application depends on third party libraries like enquire.js. When react application tries to import enquire.js on nodejs, it fails with error ReferenceError: window is not defined

Since window object is not available nodejs how to handle libraries that use window for server side rendering ?

I haven't used Webpack yet. However, I had similar issue using browserify and I solved it by creating two builds: one for browser one for node.js with list of modules to ignore. You could achieve the same effect by adding to webpack config:

{
    plugins: [
        new webpack.IgnorePlugin(/file\.js$/)
    ]
}

Then you have to make sure that you are not making any calls to enquire.js by checking if require() returned false value or object with module functions.

Well this is quite old question still if some one is looking at it.

Try

if (typeof window === 'undefined') {
  global.window = {};
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM