For a pretty large Web application I want to run multiple instances of Webpack (Encore) on the same page. When I put all the source code into a single Webpack configuration it all works. However when I have two different configurations with the same source code I always get errors like this:
lib.84f46ab6.js:19 Uncaught TypeError: __webpack_require__.n is not a function
at Object../assets/js/lib.js (lib.84f46ab6.js:19)
at __webpack_require__ (bootstrap:19)
at __webpack_exec__ (codemirror.css?f2af:1)
at codemirror.css?f2af:1
at Function.__webpack_require__.O (chunk loaded:25)
at codemirror.css?f2af:1
at webpackJsonpCallback (jsonp chunk loading:36)
at Array.forEach (<anonymous>)
at jsonp chunk loading:49
at runtime.7c0b88c9.js:146
After some research I found an article about the issue here: https://medium.com/@cliffers/how-to-run-multiple-webpack-instances-on-the-same-page-and-avoid-any-conflicts-4e2fe0f016d1
It basically says:
Webpack does not run in the global namespaceā¦so whats causing the issue? Its a webpack plugin called CommonsChunkPlugin which is used for ansyc on demand loading of code via JSONP. The plugin registers and uses a global function named window.webpackJsonp and thats where conflict occurs.
Simply change the name of the webpackJsonp function for at least one on the webpack instances running and the conflict is resolved.
But they have removed this function in Webpack 5 and I still can not figure out how to configure this correctly. Does anybody know how to solve this with the most recent version of Webpack Encore (currently 1.1.2)?
Part of my config:
// ...
const libConfig = Encore.getWebpackConfig();
// ...
// build the second configuration
const appConfig = Encore.getWebpackConfig();
appConfig.name = 'appConfig';
// Export the final configuration
module.exports = [libConfig,appConfig]
This is how multiple configurations are basically configured in Encore: https://symfony.com/doc/current/frontend/encore/advanced-config.html
Finally I solved it by adding the following setting to the configuration:
appConfig.output.chunkLoadingGlobal = 'appConfigChunkLoadingGlobal'
As simple as that. It makes sure that the global Webpack function for loading the chunks does not have the same name for both configs. It is the replacement for the old webpackJsonp
function.