I'm building a web app (react app written in es6) that is starting to get pretty big. As a result, I'm seeing unacceptably long download times for my JS file on mobile. I'm trying to wrap my mind around chunking large JS applications into chunks that are loaded on-demand. I'm using webpack, and have read this article:
https://webpack.github.io/docs/code-splitting.html
Using this article, I've split my code into app.js and vendor.js, where vendor.js contains all third party modules/plugins.
I'd like to go further and break up the app.js file into a several entry points, which would then download chunks as needed. The article above describes how to do this with CommonJS or AMD. However, I'm using ES6's native modules instead of these two options and can't find the syntax to define dependencies per file (basically, the ES6 version of .ensure() ).
My questions:
This section covers all methods available in code compiled with webpack. When using webpack to bundle your application, you can pick from a variety of module syntax styles including ES6, CommonJS, and AMD.
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.
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 supports the following module types natively: ECMAScript modules. CommonJS modules.
To answer your first question: Yes. You can definitely use ES6 modules and still load them asynchronously, but you must use the require()
function at whatever point you need the code instead of putting imports at the top of the module like normal.
Also keep in mind if you are using export default
and using babel 6, you will have to invoke the module using Module.default
(Babel 5 treats the Module
itself as the default export as a short cut, but the new behaviour is more direct. More info here
there seems to be 3 potential ingredients:
You could set separate entry points and just include the resulting builds separately in your html. But you can also use async loading based on other things (such as scrolling to a certain point, existence of certain classes/IDs).
There is a succinct guide to these at the bottom of Pete Hunt's how-to that's much easier to make sense of than the official webpack documentation.
Jonathan Creamer also has a great walkthrough in the two parts of his Advanced Webpack series of posts.
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