Code Splitting

Code Splitting

Code splitting is one of the most compelling features of webpack. It allows you to split your code into various bundles which you can then load on demand — like when a user navigates to a matching route, or on an event from the user. This allows for smaller bundles, and allows you to control resource load prioritization, which if used correctly, can have a major impact on your application load time.

There are mainly two kinds of code splitting that can be accomplished with webpack:

Resource Splitting

Vendor and CSS code splitting methods help with both caching and parallel loading.

Vendor Code Splitting

A typical application can depend on many third party libraries for framework/functionality needs. Unlike application code, code present in these libraries does not change often.

If we keep code from these libraries in its own bundle, separate from the application code, we can leverage the browser's caching mechanism to cache these files for longer durations on the end user's machine.

For this to work, the [hash] portion in the vendor filename must remain constant, regardless of application code changes. Learn how to split vendor/library code using the CommonsChunkPlugin.

CSS Splitting

You might also want to split your styles into a separate bundle, independent from application logic. This enhances cacheability of your styles and allows the browser to load the styles in-parallel with your application code, thus preventing a FOUC (flash of unstyled content).

Learn how to split CSS using the ExtractTextWebpackPlugin.

On Demand Code Splitting

While resource splitting of the previous kind requires the user to specify the split points upfront in the configuration, one can also create dynamic split points in the application code.

This can be used for more granular chunking of code, for example, per our application routes or as per predicted user behaviour. This allows the user to load non-essential assets on demand.

Learn how to split on demand using import() or require.ensure().

© JS Foundation and other contributors
Licensed under the Creative Commons Attribution License 4.0.
https://webpack.js.org/guides/code-splitting

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部