Skip to content

Trouble with SSR and splitChunks - window is not defined #2270

@smgilchrist

Description

@smgilchrist

I am currently trying to upgrade webpacker so that we can move from webpack 3 to 4. One of the big changes is changing from CommonsChunkPlugin to splitChunks, and then using javascript_packs_with_chunks_tag instead of javascript_pack_tag.

This is the set up of our current environment.js

const { environment } = require('@rails/webpacker')

const webpack = require('webpack')

environment.loaders.delete('nodeModules')

environment.plugins.append(
  'MomentEnglishOnly',
  new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en-gb/),
)

// when we use this, SSR throws an error
environment.splitChunks((config) => Object.assign({}, config, { 
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true,
        },
      }
    },
    runtimeChunk: true
  }
}))

const WebpackAssetsManifest = require('webpack-assets-manifest')
environment.plugins.insert(
  'Manifest',
  new WebpackAssetsManifest({
    entrypoints: true,
    writeToDisk: true,
    publicPath: true,
  }),
)

module.exports = environment

Here is an example of one of the packs we load:

<%= javascript_packs_with_chunks_tag 'public-pack' %>

Here is a snippet from public:

import "jquery"

// BOOTSTRAP
import '../../../vendor/assets/javascripts/bootstrap.min'

// CORE
import {} from 'jquery-ujs' //= require jquery_ujs

// FLOWPLAYER
import '../bundles/Flowplayer/flowplayer'

import Enrollment from '../bundles/Enrollment/components/Enrollment';
import SeoSubjectEnrollment from '../bundles/Enrollment/components/SeoSubjectEnrollment';
import SeoExamReviewsSchool from '../bundles/Enrollment/components/SeoExamReviewsSchool';

import ReactOnRails from 'react-on-rails';

ReactOnRails.register({
  Enrollment,
  SeoSubjectEnrollment,
  SeoExamReviewsSchool,
})

The splitChunks seem to be working as expected, and the app works as intended when I turn server side rendering off for all the react components, but when I turn the server side rendering on, I keep getting a window is not defined error.

I've tried a couple suggestions on how turn OFF splitChunks for server side rendering only, but the results ended up with splitChunks being turned off for both server side and client side.

Please let me know if there is anything else I should include in this, but essentially I am trying to find a solution to not use splitChunks when it's server side.

Metadata

Metadata

Assignees

No one assigned

    Labels

    supportQuestions or unspecific problems

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions