I’ve struggled with the answer to this question for months. While I’ve realized it is possible, the examples I’ve found are bad, or do not work. And the documentation for webpack is as always arcane on the subject, making it very difficult to do it from scratch yourself.
However, I have finally managed to get it working through the Code Splitting plugin. Below is the configuration to use for webpack:
Running webpack (through gulp in my case) after this should result in the following:
This results in webpack creating four different modules. The
must be included on every page, and includes the common code for the modules
(libraries etc.) and also the webpack bootstrap code. The other modules
contains the compiled code from that folder.
Then the question is; how to load the modules dynamically on demand? In my case the entire page is NOT a React component, only parts of the page are. And I mount separate React components in different places in the DOM.
To solve this, I have a function that wraps
ReactDOM.render with a check
if the module is loaded, in that case it just forwards the call, otherwise
it injects the script tag for that module.
This solution works great for intermingling React and native HTML for a page.
If your situation is different, and your entire page is a React app you will
need to modify this approach, by using
instead. I have not tried this yet, but it should not require any changes to
the webpack configuration above to implement.