-
Notifications
You must be signed in to change notification settings - Fork 0
long term caching.cn
To effectively cache your files, they should have a hash or version in their URL. You can emit or move the output files manually in a folder called v1.3
. But this has several disadvantages: Extra work for the developer and unchanged files aren't loaded from cache.
为了有效地缓存文件,它们的 URL 上应该有一个 hash 值或者版本号。你可以手动发送或者移动输出文件到一个叫v1.3
的文件夹。但这样子有几个缺点:开发者额外的工作,未曾变化的文件不能从缓存加载(浏览器端)
Webpack can add hashes for the files to the filename. Loaders that emit files (worker-loader, file-loader) already do this. For the chunks you have to enable it. There are two levels: webpack 可以为文件的名字添加 hash。发送文件的 loader(worker-loader, file-loader)已经这样做了。对于 chunk 则需要自行开启。有两种级别:
- Compute a hash of all chunks and add it.
- Compute a hash per chunk and add it.
- 计算所有 chunk 的总体 hash
- 计算每个 chunk 的独立 hash
Option 1 is enabled by adding [hash]
to the filename config options:
开启选项 1 可通过向文件名的配置选项添加[hash]
webpack ./entry output.[hash].bundle.js
{
output: {
path: path.join(__dirname, "assets", "[hash]"),
publicPath: "assets/[hash]/",
filename: "output.[hash].bundle.js",
chunkFilename: "[id].[hash].bundle.js"
}
}
Option 2 is enabled by adding [chunkhash]
to the chunk filename config option
开启选项 2 可通过向 chunk 文件名的配置选项添加[chunkhash]
--output-chunk-file [chunkhash].js
output: { chunkFilename: "[chunkhash].bundle.js" }
Note that you need to reference the entry chunk with its hash in your HTML. You may want to extract the hash or the filename from the stats.
注意你需要在 HTML 中引用带有 hash 的入口 chunk。你可能想从统计数据中提取 hash 或者文件名。
In combination with Hot Code Replacement you must use option 1, but not on the publicPath
config option.
结合代码热替换,你必须使用选项 1,但不要在publicPath
选项上使用。
You probably want to access the final filename of the asset to embed it into your HTML. This information is available in the webpack stats. If you are using the CLI you can run it with --json
to get the stats as JSON to stdout.
你可能想访问资源的最终的文件名以将其嵌入到 HTML 文件中。此类信息可在 webpack 的统计数据中获取。如果你在使用 CLI 工具,你可以使用--json
运行来将统计信息以 JSON 的格式输出到标准输出中。
You can add a plugin such as assets-webpack-plugin to your configuration which allows you to access the stats object. Here is an example how to write it into a file: 你可以添加一个插件如assets-webpack-plugin到配置中,以获取配置对象。下例展示了如何将其输出到文件:
plugins: [
function() {
this.plugin("done", function(stats) {
require("fs").writeFileSync(
path.join(__dirname, "..", "stats.json"),
JSON.stringify(stats.toJson()));
});
}
]
The stats JSON contains a useful property assetsByChunkName
which is a object containing chunk name as key and filename(s) as value.
JSON 形式的统计信息包含一个有用的属性assetsByChunkName
,一个以 chunk 名为键、文件名为值的对象。
Note: It's an array if you are emitting multiple assets per chunk. I. e. a JavaScript file and a SourceMap. The first one is your JavaScript source. 注意:如果每个 chunk 都发送多个资源,值是一个数组。譬如:一个 JavaScript 文件和一个 SourceMap。第一个数组元素是你的 JavaScript 的文件名。