zlx362211854 / daily-study

每日一个知识点总结,以issue的形式体现
10 stars 6 forks source link

119. webpack 文件hash的几种方式 #176

Open zlx362211854 opened 4 years ago

zlx362211854 commented 4 years ago

webpack中对于输出文件有三种hash方式:

goldEli commented 4 years ago

为什么要文件要加 haah 值?

为了控制浏览器缓存,当文件名未发生改变时,浏览器会直接从缓存中读取。

如何加 hash?

总共有三种方法:

hash

{
    enter: "index.js",
    output: {
      filename: "[name].[hash].js",
      path: path.resolve(__dirname, 'dist')
    } 
}

如上设置每次 build 对应的文件 hash 值都会发生改变。

如果有多个入口文件,如何只控制某个入口文件的 hash 呢? 这需要用到 chunkhash。

chunkhash

{
    entry: {
      index: "./index.js",
      another: "./another.js"
    },
    output: {
      filename: "[name].[chunkhash].js",
      path: path.resolve(__dirname, 'dist')
    }
}

当 index 的文件发生改变就不会影响到 another.js 的 hash。

但是有可能,一个 chunk 也会 codespilt 成多个文件,当只有某个文件发生改变也会影响到所有的 chunk。所以最好让 hash 控制到每个文件,这里就需要用到 contenthash

contenthash

{
    entry: {
      index: "./index.js",
      another: "./another.js"
    },
    output: {
      filename: "[name].[contenthash].js",
      path: path.resolve(__dirname, 'dist')
    }
}

Reference

Hash vs chunkhash vs ContentHash