AndreGeng / AndreGeng.github.io

blog repository
1 stars 0 forks source link

webpack: hash vs chunkhash vs contenthash #33

Open AndreGeng opened 5 years ago

AndreGeng commented 5 years ago

这里尝试解释下webpack中几种不同的hash的用法,包含以下内容:

  1. 为什么需要hash
  2. webpack有哪些类型的hash
  3. 每种hash的用法

为什么需要hash

浏览器缓存需要

webpack中的hash类型分类

  1. hash
  2. chunkhash
  3. contenthash

    用法

  4. hash hash是与webpack build相关的概念,只要一次build中所有文件的[hash]插值都是相同的
  5. chunkhash chunkhash是chunk相关的,一次build中不同的chunk的[chunkhash]插值是不同的
  6. contenthash conenthash是插件ExtractTextWebpackPlugin提供的,它是根据提取出的内容所计算出的值。如果你在提取css的文件名中使用了[chunkhash],你会发现生成的chunk文件的hash和提取出css文件的hash是相同的,这时如果我们更改了css文件的内容。再次打包,你会发现css文件的hash值还是原来的。所以这里应该使用contenthash

ps: extract-text-webpack-plugin和webpack4是不兼容的,webpack4下面请使用mini-css-extract-plugin

Reference: webpack hash