网页 综合 更新时间 2026-11-14 09:16:44

Code Splitting | webpack

自动蜘蛛 webpack.js.org 正文约 5999 字
Code Splitting | webpack
This guide extends the example provided in Getting Started. Please make sure you are at least familiar with the example provided there and the Output Management chapter.
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. It can be used to achieve smaller bundles and control resource load prioritization which, if used correctly, can have a major impact on load time.
There are three general approaches to code splitting available:
This is by far the easiest and most intuitive way to split code. However, it is more manual and has some pitfalls we will go over. Let's take a look at how we might split another module from the main bundle:
This will yield the following build result:
As mentioned there are some pitfalls to this approach:
The first of these two points is definitely an issue for our example, as lodash is also imported within ./src/index.js and will thus be duplicated in both bundles. Let's remove this duplication in next section.
The dependOn option allows to share the modules between the chunks:
If we're going to use multiple entry points on a single HTML page, optimization.runtimeChunk: 'single' is needed too, otherwise we could get into trouble described here.
And here's the result of build:
As you can see there's another runtime.bundle.js file generated besides shared.bundle.js, index.bundle.js and another.bundle.js.
Although using multiple entry points per page is allowed in webpack, it should be avoided when possible in favor of an entry point with multiple imports: entry: { page: ['./analytics', './app'] }. This results in a better optimization and consistent execution order when using async script tags.
The SplitChunksPlugin allows us to extract common dependencies into an existing entry chunk or an entirely new chunk. Let's use this to de-duplicate the lodash dependency from the previous example:
With the optimization.splitChunks configuration option in place, we should now see the duplicate dependency removed from our index.bundle.js and another.bundle.js. The plugin should notice that we've separated lodash out to a separate chunk and remove the dead weight from our main bundle. However, it's important to note that common dependencies are only extracted into a separate chunk if they meet the size thresholds specified by webpack.
Let's do an npm run build to see if it worked:
CSS is split the same way: webpack extracts a stylesheet per chunk on its own, so a lazily imported CSS file arrives with the chunk that needs it — see Native CSS.
Two similar techniques are supported by webpack when it comes to dynamic code splitting. The first and recommended approach is to use the import() syntax that conforms to the ECMAScript proposal for dynamic imports. The legacy, webpack-specific approach is to use require.ensure. Let's try using the first of these two approaches...
import() calls use promises internally. If you use import() with older browsers (e.g., IE 11), remember to shim Promise using a polyfill such as es6-promise or promise-polyfill.
Before we start, let's remove the extra entry and optimization.splitChunks from our configuration in the above example as they won't be needed for this next demonstration:
We'll also update our project to remove the now unused files:
Now, instead of statically importing lodash, we'll use dynamic importing to separate a chunk:
The reason we need default is that since webpack 4, when importing a CommonJS module, the import will no longer resolve to the value of module.exports, it will instead create an artificial namespace object for the CommonJS module. For more information on the reason behind this, read webpack 4: import() and CommonJs.
Let's run webpack to see lodash separated out to a separate bundle:
You can also use magic comment webpackExports with import() to expose specific exports from a dynamically imported module:
This can help webpack tree shake other unused exports. See Magic Comments for details.
As import() returns a promise, it can be used with async functions. Here's how it would simplify the code:
It is possible to provide a dynamic expression to import() when you might need to import specific module based on a computed variable later.
When using dynamic import() or code splitting, webpack may throw a ChunkLoadError if a chunk fails to load at runtime.
This error typically indicates that the requested chunk could not be executed or resolved properly. In some cases, the browser’s underlying network or script loading error may not be fully reflected in the ChunkLoadError message itself.
If you encounter this error:
For more context, see related discussion in the webpack issue tracker.
Webpack 4.6.0+ adds support for prefetching and preloading.
Using these inline directives while declaring your imports allows webpack to output “Resource Hint” which tells the browser that for:
An example of this is having a HomePage component, which renders a LoginButton component which then on demand loads a LoginModal component after being clicked.
This will result in <link rel="prefetch" href="login-modal-chunk.js"> being appended in the head of the page, which will instruct the browser to prefetch in idle time the login-modal-chunk.js file.
webpack will add the prefetch hint once the parent chunk has been loaded.
Preload directive has a bunch of differences compared to prefetch:
An example of this can be having a Component which always depends on a big library that should be in a separate chunk.
Let's imagine a component ChartComponent which needs a huge ChartingLibrary. It displays a LoadingIndicator when rendered and instantly does an on demand import of ChartingLibrary:
When a page which uses the ChartComponent is requested, the charting-library-chunk is also requested via <link rel="preload">. Assuming the page-chunk is smaller and finishes faster, the page will be displayed with a LoadingIndicator, until
访问原文 返回搜索 https://webpack.js.org/guides/code-splitting/
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。