gpt4 book ai didi

javascript - webpack [hash] 和 [chunkhash] 的用途是什么?

转载 作者:行者123 更新时间:2023-12-03 02:00:01 25 4
gpt4 key购买 nike

有人可以告诉我 [hash] 和 [chunkhash] 的目的是什么以及它们来自哪里吗?

output: {
path: "/home/proj/cdn/assets/[hash]",
publicPath: "http://cdn.example.com/assets/[hash]/"
}

最佳答案

这一点对我来说暂时并不明显,所以我认为它值得一些更详细的解释。

官方文档内容:

来自官方的简单说明documentation关于他们的目的:

A simple way to ensure the browser picks up changed files is by using output.filename substitutions. The [hash] substitution can be used to include a build-specific hash in the filename, however it's even better to use the [contenthash] substitution which is the hash of the content of a file, which is different for each asset.

再一一解释来自documentationoutput.filename :

  • [hash]是“为每个构建生成的唯一哈希值”
  • [chunkhash]是“基于每个 block 的内容”
  • [contenthash]是“为提取的内容生成的”

让我们通过示例使其更容易理解:

我的src中有3个文件目录:index.js , index.css , vendors.js

我的示例 Webpack 配置中的相关部分:
(不是完整的工作配置!)

entry: {
index: ["./src/index.js", "./src/index.css"],
vendors: ["./src/vendors.js"]
},
output: {
filename: "[name].[hash].js"
}
plugins: [
new MiniCssExtractPlugin({
filename: "[name].[hash].css"
})
]

所以我有 2 个 block 名称,indexvendors ,但是看看index chunk 还将有 css内容,因为它导入了 css数组中的文件。构建时,css部分将使用 MiniCssExtractPlugin 导出到单独的文件(就我而言)但 Webpack 知道 index.jsindex.css属于同一个 block 。

现在让我们尝试使用不同的哈希类型来构建它。 (同样更改两个 filename 选项)

使用[哈希]:

enter image description here

每个文件都有相同的哈希值,因为 [hash]是根据我们所有使用的源文件生成的。如果我重新运行构建而不更改任何内容,生成的哈希将保持不变。如果我只编辑一个文件,那么哈希值将会更改,并且我生成的所有 bundle 的名称中都将包含此新哈希值。

使用 [chunkhash]:

enter image description here

如您所见,第一个和第二个文件来自同一个 index block ,因此它们的名称中具有相同的哈希值。这是因为[chunkhash]是根据给定 block 的全部内容生成的。所以如果我编辑的话,比如 index.css并重新构建来自 index 的文件chunk 将有一个新的哈希值,但来自 vendors 的哈希值 block 将保持与之前相同。

使用 [contenthash]:

enter image description here

这一点是显而易见的。每个生成的文件的名称中都有一个唯一的哈希值,该哈希值是根据该文件的内容计算得出的。如果我改变的话,比如 index.css重新构建,仅生成index.css将有一个新的哈希值。

关于javascript - webpack [hash] 和 [chunkhash] 的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35176489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com