Change Webpack's publicPath on the fly
Hello there, first I would like to give you a warning about my writing — it is horrible and I am not the best writer in the world so be prepared 😃.
In the last few days I was trying to split our large SPA to more little dynamically loaded chunks. This part is pretty easy as only thing you have to do is to tell webpack how to name your chunks and the second thing I had to do was to install Babel Syntax Dynamic Import so `import()` could be parsed without any error.
The most frustrating part was to correctly set up the dynamic path as I was not even sure if it was possible with Webpack. The problem is that the company I work for has many different customers and the application can be served from different URL for every customer and that was causing trouble because was loading chunks from '/dist/' folder without correct path.
Thanks to clever guys from https://gitter.im/webpack/webpack I discovered that publicPath can be set dynamically on the fly using __webpack_public_path__ = URL.
This has to be set on top of your entry file or imported from ES6 module (again as first import in your entry file).
In our case we read URL from hidden input in index HTML file and set it as webpack's publicPath on the fly.
__webpack_public_path__ = document.getElementById('webRoot').value;
If you get errors about undeclared variable or something similar then you have to update your ESLint config.
Hopefully this little article makes sense to you and it will help you 😃.
PS: Don't be like me and first check Webpack's documentation, all the information is right there 😃 — https://webpack.js.org/guides/public-path/#set-value-on-the-fly. For some reason I was avoiding it so I didn't find it there for the first time.