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

Caching | webpack

自动蜘蛛 webpack.js.org 正文约 6000 字
Caching | webpack
The examples in this guide stem from getting started, output management and code splitting.
So we're using webpack to bundle our modular application which yields a deployable /dist directory. Once the contents of /dist have been deployed to a server, clients (typically browsers) will hit that server to grab the site and its assets. The last step can be time consuming, which is why browsers use a technique called caching. This allows sites to load faster with less unnecessary network traffic. However, it can also cause headaches when you need new code to be picked up.
This guide focuses on the configuration needed to ensure files produced by webpack compilation can remain cached unless their content has changed.
We can use the output.filename substitutions setting to define the names of our output files. Webpack provides a method of templating the filenames using bracketed strings called substitutions. The [contenthash] substitution will add a unique hash based on the content of an asset. When the asset's content changes, [contenthash] will change as well.
Let's get our project set up using the example from getting started, letting webpack write the page for us as in output management, so we don't have to deal with maintaining our index.html file manually:
output.html writes a document around the entry and injects its chunks, so the page tracks the hashed filenames on every build.
Running our build script, npm run build, with this configuration should produce the following output:
As you can see the bundle's name now reflects its content (via the hash). If we run another build without making any changes, we'd expect that filename to stay the same. However, if we were to run it again, we may find that this is not the case:
This is because webpack includes certain boilerplate, specifically the runtime and manifest, in the entry chunk.
Output may differ depending on your current webpack version. Newer versions may not have all the same issues with hashing as some older versions, but we still recommend the following steps to be safe.
As we learned in code splitting, the SplitChunksPlugin can be used to split modules out into separate bundles. Webpack provides an optimization feature to split runtime code into a separate chunk using the optimization.runtimeChunk option. Set it to single to create a single runtime bundle for all chunks:
Let's run another build to see the extracted runtime bundle:
It's also good practice to extract third-party libraries, such as lodash or react, to a separate vendor chunk as they are less likely to change than our local source code. This step will allow clients to request even less from the server to stay up to date. This can be done by using the cacheGroups option of the SplitChunksPlugin demonstrated in Example 2 of SplitChunksPlugin. Lets add optimization.splitChunks with cacheGroups with next params and build:
Let's run another build to see our new vendor bundle:
We can now see that our main bundle does not contain vendor code from node_modules directory and is down in size to 240 bytes!
Let's add another module, print.js, to our project:
Running another build, we would expect only our main bundle's hash to change, however...
... we can see that all three have. This happens when each module.id is assigned from the resolving order (optimization.moduleIds: 'natural'), which webpack 5 only does by default for mode: 'none'. Meaning when the order of resolving is changed, the IDs will be changed as well. To recap:
The first and last are expected, it's the vendor hash we want to fix. production mode already defaults optimization.moduleIds to 'deterministic' and development mode to 'named', both stable across builds; setting 'deterministic' explicitly keeps the ids stable regardless of mode:
Now, despite any new local dependencies, our vendor hash should stay consistent between builds:
And let's modify our src/index.js to temporarily remove that extra dependency:
And finally run our build again:
We can see that both builds yielded 55e79e5927a639d21a1b in the vendor bundle's filename.
Content hashes make every deploy emit a new set of filenames, and that interacts with code splitting in a way worth planning for: a visitor who loaded the page before the deploy is running the old entry chunk, which asks for the old filename of an async chunk. If that file is gone from the server, the import() rejects and the application sees a ChunkLoadError — usually as a route or a lazily loaded widget that fails for exactly as long as the tab stays open.
The fix is on the deployment side, not in the configuration. Two measures cover it:
Keep the previous build's assets around. Serving old files costs little and makes the error disappear for anyone who loaded the page before the deploy. Copy the new build over the old one instead of replacing the directory; if you clean the output directory on build, output.clean accepts a keep predicate, and a CDN can expire the old objects after a day or so rather than on the next deploy.
Handle the rejection anyway. No retention window covers a tab left open over a weekend, so treat a failed chunk load as "this page is out of date" and reload it:
Reloading unconditionally will loop if the chunk is missing for another reason — a broken deploy, an offline user. Reload at most once (record it in sessionStorage), and surface a "new version available, reload" prompt instead when you already have one.
Two related options: output.chunkLoadTimeout sets how long webpack waits before rejecting, and output.crossOriginLoading is needed to get a useful error rather than an opaque one when chunks are served from a different origin.
Caching can be complicated, but the benefit to application or site users makes it worth the effort. See the Further Reading section below to learn more.
Copyright OpenJS Foundation and webpack contributors. All rights reserved. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJ
访问原文 返回搜索 https://webpack.js.org/guides/caching/
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。