Is it possible to get the benefits of both dynamic imports and split chunks (SplitChunksPlugin)?
When I use dynamic imports I get one chunk per library that has been dynamically imported. However, anything that is statically imported gets added to the same (big) bundle. pseudocode:
// my-module.js
const foolib = await import('foolib');
export default foolib('some-arg');
results in:
foolib.bundle.js
contains only foolib
, greatmy-module.bundle.js
contains my-module
and every static import, not greatDoes the other half of what I want. pseudocode:
// my-module.js
import foolib from 'foolib';
export default foolib('some-arg');
results in:
my-module.bundle.js
contains my-module
only, greatvendors.bundle.js
contains all the node_modules dependencies, greatBut, this solution lacks dynamic loading.
The idea is that this config would get me all the things.
foolib.bundle.js
contains only foolib
because it was dynamically importedmy-module.bundle.js
contains my-module
onlyvendors.bundle.js
contains all the node_modules dependenciesThe results I've gotten so far are that dynamic imports are not considered when you add the optimization
key (add the splitChunks) to the webpack.config.js
.
In what direction should I further investigate? My hunch is that maybe I can find a way to better tune the way dynamic imports is generating chunks, but maybe I'm wrong?
Whenever you import a file in your code, Webpack will look for it in the project directory and copy it to the build folder with a new name, then Webpack replaces the import code in your bundled JavaScript file with the path to the newly copied file.
Code splitting is one of the most compelling features of webpack. This feature allows you to split your code into various bundles which can then be loaded on demand or in parallel.
Webpack injects some code into main. js which takes care of lazy loading async chunks and stops from loading same chunks again and again. When a route changes, React router calls a Webpack function to load a chunk file and Webpack after done loading runs it, which chunk then would internally ask React to do something.
Dynamic module imports are very similar to static module imports, but the code is loaded only when it is needed instead of being loaded right away. This means your page load speed will be much quicker and the user will only ever load JavaScript code that they are actually going to use.
Check out Paragons. It uses both dynamic imports and split chunks. The BundleAnalyzerPlugin plugin is setup for the production mode. After you generate my-app, you can do npm run build
and the client report will be emitted in the dist directory. Here is a sample screenshot:
You can also check out the Webpack config.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With