Search code examples
javascriptwebpackwebpack-4

Webpack 4 output.library failed to add object to window


I am upgrading a project from Webpack 3 to Webpack 4.

Currently I have a file at /my-proj/apps/myApp1/wrappers/clientWrapper.js which is

export default {
  a: 1,
  b: 2,
};

Webpack client config:

entry: {
  index: [
    'core-js/modules/es6.symbol',
    'regenerator-runtime/runtime',
    'core-js/fn/object/assign',
    'core-js/fn/object/values',
    'core-js/fn/object/entries',
    'react-hot-loader/patch',
    'webpack-hot-middleware/client?reload=true&path=http://0.0.0.0:3000/__webpack_hmr',
    '/my-proj/apps/myApp1/wrappers/clientWrapper.js'
  ]
},
output: {
  path: '/my-proj/build/client',
  filename: '[name].js',
  chunkFilename: '[name]-[chunkhash].js',
  library: [ 'myApp1', '[name]' ],
  libraryTarget: 'umd',
  publicPath: 'http://0.0.0.0:3000/client/'
}
// ...

Webpack server config:

entry: {
  index: [
    '/my-proj/apps/myApp1/wrappers/serverWrapper.js'
  ]
},
output: {
  path: '/my-proj/build/server',
  filename: '[name].js',
  chunkFilename: '[name]-[chunkhash].js',
  library: [ 'myApp1', '[name]' ],
  libraryTarget: 'commonjs2',
  publicPath: 'http://0.0.0.0:3000/client/'
}
// ...

Since the value of [name] will be index in this case, so by Webpack's output.library,

the above config can help add the object to window.myApp1.index.

More info about this way you can check at

The client browser console now will print

window.myApp1.index.default = {
  a: 1,
  b: 2,
}

The screenshot is for window.myApp1:

enter image description here

However, after upgrading to Webpack 4, with same Webpack entry and output config, it failed to add the object to window.myApp1.index:

window.myApp1.index = undefined

enter image description here

Any idea? Thanks


Solution

  • I located the issue, which is caused by the new added Webpack 4's

    optimization: {
     splitChunks: {
       chunks: 'all',
     },
    },
    

    which I totally forget.

    Once removing them, it works again. I will have to figure out a way later to make the app work with splitChunks.

    If I figured out, I will post back.