How my application is split into chunks
My applications main and only entry chunk contains some common logic that is reused throughout the application such has layouting or helper methods and components related to authentication such as login/registration dialogs. This chunk has react
, react-dom
, redux
, react-router
and some other libs from node_modules
directory in its dependency tree because they are being used by the authentication components.
All those dependencies are bundled into an app.js
file that is always initially loaded. Whenever the user starts to use some part of the application that requires a logged in user - such as dashboards, forms and other app functionality, additional javascript chunks comprising that functionality are loaded. Those additional chunks are automatically generated by webpack
because of import()
calls distributed throughout the applications code.
When a new user loads the app and is not logged in, app.js
is loaded and the user is presented with a login mask. After a user has successfully logged in and is redirected to the main dashboard, the code of the dashboard is asynchronously loaded. This code, automatically built into a dashboard.js
chunk by webpack
, also depends on a lot of the libraries already baked into the app.js
chunk (e.g. react
, react-dom
etc). Because the dashboard.js
chunk does not duplicate those libraries, it is quite small compared to the app.js
.
To make good use of browser caching, all of those chunks (in this simplified
example: the entry chunk app.js
and the dynamic chunk dashboard.js
) have a
[chunkhash]
in their name. In comparison to library code from node_modules
, both the code of the dynamic chunks and the parts of the app.js
that are actual application code change quite a lot.
What i would like to do
I would like to configure webpack
in a way that detects which libraries from
node_modules
are used in more than 2 (or any configurable number) of chunks and
automatically split those into an additional chunk, vendor.js
.
This chunk should contain the library parts of the current app.js
that don't change often so the user doesn't often re-download library code.
From what i've understood, something like this can be done with
CommonsChunkPlugin
when manually adding lots of entry chunks. Can i also do
this with dynamic code splitting performed with import()
calls?
Example
I might use lodash.partialRight
somewhere in in dashboard.js
. As long as it is only used there, i want it to be bundled with dashboard.js
. The moment i also use it in the login/registration process, it should not be bundled into the
app.js
the way it is now but should instead automatically be bundled into vendor.js
with other libraries that are re-used across chunks.