webpackThe fingerprint strategy is one of the solutions to realize incremental front-end update. By adding to the filehashSuffix to maximize the use of caching

Webpack provides three hash generation methods:

  • hash: is related to the entire project build. Whenever a file is modified, the hash value of the entire project changes
  • chunkHash: Hash of the module, which changes the hash value according to the module modification
  • contentHash: Hash value that will change if the article content is modified

According to the description, we can roughly distinguish between chunkHash for JS packaging and contentHash for CSS file packaging. Let’s do it.

1.Hash

directory

. ├ ─ ─ dist ├ ─ ─ package - lock. Json ├ ─ ─ package. The json ├ ─ ─ the SRC │ ├ ─ ─ page0. Js │ └ ─ ─ page1. Js └ ─ ─ webpack. Config. JsCopy the code

webpack.config.js

output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name]_[hash:8].js'
},
Copy the code

The output

page0.js

You can see that the hash value of both files has changed. This was definitely not what we needed in real development, so chunkHash was ready to play at this point.

2.chunkHash

webpack.config.js

output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name]_[chunkhash:8].js'
},
Copy the code

page0.js

page0.js
page1
page1.js

But this raises the question, what if I have CSS content in my file? Can you peel it off? When js changes, does it not affect the CSS version? Of course you can, and that’s where contentHash comes in

3.contentHash

We introduce a.scss file in page0.js

import './style.scss'
Copy the code

What we need to do is to strip the CSS file and add contentHash. Here we need to use a plugin mini-CSs-extract-plugin.

  module: {
    rules: [
      {
        test: /.scss$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader'.'sass-loader'
        ]
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name]_[contenthash:8].css'})]};Copy the code

Pack to see

page1.js

page0.js
css

Over.

Link to the article

Webpack Learning path (5) Loader introduction and common loader introduction

Webpack-hot-middleware enables hot updates

Webpack-dev – Middleware

Webpack-dev-server implements hot update

Webpack learning path (1) basic configuration

I am moving forward.