How to run multiple webpack instances on the same page…and avoid any conflicts

Last week i was developing my first Angular 2 app. It was a simple widget based app that needed to be installed on multiple webpages on multiple sites.

Using the Angular CLI tool, development was fairly painless. All was well and after building the final app in production mode i was feeling confident.

The Problem

I then went to install the app on a webpage within a Sqaurespace website. And thats where the errors started.

Uncaught d {__zone_symbol__error: Error: Zone already loaded.

Uncaught TypeError: __webpack_require__(…) is not a function`

I was getting a couple of different types of errors based on two different Squarespace websites i was trying (running different themes).

Due to my lack of experience with webpack it took me a whole day to figure out what was wrong. After a couple of table head banging moments i managed to figure it out.

The Solution

From my first Zone already loaded error i thought that the issue lied with Zone.js but its nothing to do with that. The issue happens when a webpage loads two or more JS scripts that run different instances of webpack. Ultimately its a webpack conflict.

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.

However do no fear…webpack configuration setting to the rescue!

https://webpack.js.org/configuration/output/#output-jsonpfunction

This is the solution. Simply change the name of the webpackJsonp function for at least one on the webpack instances running and the conflict is resolved.

Hope this helps anyone with the same issue. This kind of issue can very fustrating for newcomers to webpack.