ShakaCode | ShakaCode Blog | Rails On Maui Blog | Rails | ReactJs | JavaScript | Webpack | Productivity |

ERROR when compiling base_js_code! See file tmp/base_js_code.js to correlate line numbers of error. Error is ReferenceError: window is not defined


#1

Hi, I’m seeing error while trying code splitting a component in my project.
ReactOnRails 7.0.4 + server render.

The SSR is working fine, until I start to code split one of the component loading.
Please see following code:

const asyncComponent = (props) => {
  import('../asyncComponent').then(component => {
    document.body.appendChild(<component />);
  });
}
output: {
  path: path.resolve(__dirname,'../app/assets/', 'webpack'),
  publicPath: '/asset_pipeline/',
  filename: '[name].js',
  chunkFilename: '[name].js',
},

I’m seeing following error:

ERROR in SERVER PRERENDERING
Encountered error: "ReferenceError: window is not defined"

...

(execjs):38:11
(execjs):181:11
/Users/al/.rbenv/versions/2.3.4/lib/ruby/gems/2.3.0/gems/execjs-2.7.0/lib/execjs/ruby_racer_runtime.rb:15:in `rescue in block in initialize'
/Users/al/.rbenv/versions/2.3.4/lib/ruby/gems/2.3.0/gems/execjs-2.7.0/lib/execjs/ruby_racer_runtime.rb:12:in `block in initialize'
/Users/al/.rbenv/versions/2.3.4/lib/ruby/gems/2.3.0/gems/execjs-2.7.0/lib/execjs/ruby_racer_runtime.rb:75:in `block in lock'
/Users/al/.rbenv/versions/2.3.4/lib/ruby/gems/2.3.0/gems/therubyracer-0.10.2/lib/v8/c/locker.rb:13:in `Locker'

How to solve it or dig into it?
Thanks!


#2

The message is clear. You are accessing “window” in your server rendering code. window is not available on the server.

Please consider our Pro Support plan for React on Rails. I hope we can help you out more. Feel free to book a time to meet to discuss this: https://calendly.com/justingordon.

Thanks!


#3

Thanks Justin. It might be caused by the webpack packaging.

I’ll async load the data in that component instead of async load the component.