He who knows others is wise, he who knows himself is bright, he who wins others is powerful, and he who wins is strong. Lao tzu

Introduction to the

There are three kinds of hash that can be configured in webpack, they are hash, chunkhash and Contenthash. They are incorrect and can be used for different configurations. The prime Minister needs to know the difference between these three kinds of hash, which scenario is suitable for use.

Hash All files have the same hash value. If the changed content is different from the previous one, all the hashes are changed, which does not make cache sense

Chunkhash When there are multiple chunks and multiple bundles, if the contents of only one chunk and one bundle change, the hash of the other bundles will change because they all share the same hash. In this case, chunkhash is used. It parses dependent files according to different Entry files, constructs corresponding chunks, and generates corresponding hash values.

Contenthash will import the CSS file in js when packing, because they are the same entry file, if I only change the JS code, but his CSS extraction will also change the hash when generating the CSS file. This is where Contenthash comes in.

Let’s directly verify the above conjecture with code.

A simple WebPack configuration

We will now just create a WebPack configuration that compiles JS as follows:

  1. Create an empty file and open it in a folderbash or cmd.
  2. npm init -ygeneratepackage.json.
  3. If you install itcnpm or yarnIs executedcnpm i webpack webpack-cli -DTo installwebpackThe package.
  4. createsrcIn thesrcInternal createchunk0.js,chunk1.js,common.js,index.js,style.cssAnd write internal code
  5. Created in the project root directorywebpack.config.js
  6. Directly in thecmdRunning in thewebpack

The file directories are as follows:

Here is the code chunk0.js

export default function add (a, b) {
  return a + b;
};
Copy the code

chunk1.js

export default function flow () {
  return 'flow';
};
Copy the code

common.js

export default function commonJs () {
  return 'commonJs';
};
Copy the code

index.js

import add from './chunk0.js';
import commonJs from './common';
console.log(add(1.2));
console.log(commonJs());
Copy the code

style.css

body {
  background: # 000;
}
Copy the code

webpack.config.js

module.exports = {
  mode: "production".// If you do not add it, you will be warned
  entry: {
    index: "./src/index.js".// an entry file
    chunk1: "./src/chunk1.js" // Two entry files
  },
  output: {
    filename: "[name].[hash].js" // Export file}}Copy the code

hash

We run WebPack directly and the result looks like the following:

There is only one hash, and all files have the same hash:

If we change the code in chunk1.js:

export default function flow () {
  return 'flow1'; // flow => folw1
};
Copy the code

Run webpack again and see that all the hashes have changed, as shown below:

If you want to modify chunk1.js without changing index.js, you need to use Chunkhash.

chunkhash

  • The first step is to modify webpack.config.js
module.exports = {
  mode: "production".entry: {
    index: "./src/index.js".chunk1: "./src/chunk1.js"
  },
  output: {
    filename: "[name].[chunkhash].js" // hash => chunkhash}}Copy the code
  • Step two we runwebpack

chunk
hash

  • The third part we modifychunk1.js
export default function flow () {
  return 'flow11111'; // flow1 => flow11111
};
Copy the code
  • Run againwebpack

According to the picture, we can see that the hash of chunk1.js has changed, while the hash of index.js has not changed, which has achieved our expected effect and is good for our online cache.

contenthash

But when we reference a CSS file in a JS file, if we change the contents of the CSS file, the contents of our CSS will notice that the hash of the entire bundle will also be updated. To import CSS, and to extract and compress CSS to generate a CSS file, we need to use a Webpack plug-in, called MiniCssExtractPlugin, he can help me extract CSS to CSS file, and compress CSS.

  • The first step is installationcss-loader,mini-css-extract-pluginpackage
cnpm install css-loader mini-css-extract-plugin -D
Copy the code
  • Step 2 Modifywebpack.config.jsThe following
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); / / new
module.exports = {
  mode: "production".entry: {
    index: "./src/index.js".chunk1: "./src/chunk1.js"
  },
  output: {
    filename: "[name].[chunkhash].js"
  },
  module: { / / new
    rules: [
      {
        test: /\.css$/.use: [
          MiniCssExtractPlugin.loader, 
          "css-loader"]]}},plugins: [ / / new
    // Extract the CSS plug-in
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: "[name].[chunkhash].css"}})];Copy the code
  • Step 3 Run webPack

If you look at the code, you can see that index.css and index.js have the same hash.

  • Step 4 Modify style.css
html {
  font-size: 13px;
}
Copy the code
  • Step 5 Run webPack

The contenthash is needed to update the hash, as the style.css file is only modified and its index.js file is updated.

  • Step 6 Modifywebpack.config.jsAnd run WebPack
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); / / new
module.exports = {
  mode: "production".entry: {
    index: "./src/index.js".chunk1: "./src/chunk1.js"
  },
  output: {
    filename: "[name].[chunkhash].js"
  },
  module: { / / new
    rules: [
      {
        test: /\.css$/.use: [
          MiniCssExtractPlugin.loader, 
          "css-loader"]]}},plugins: [ / / new
    // Extract the CSS plug-in
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: "[name].[contenthash].css"}})];Copy the code

  • Modify thecommon.jsRun WebPack directly
export default function commonJs () {
  return 'commonJs1';
};
Copy the code

See that the hash of our CSS file does not change when we change the JS.

Note that when contenthash is used, if you modify the JS file, the CSS file hash will not change, but if you modify the JS file, the CSS file hash will change as well.

conclusion

Hash All files have the same hash value. Chunkhash parses dependent files according to different Entry files, constructs corresponding chunks, and generates corresponding hash values. Contenthash calculation is related to the content of the file itself and is mainly used to extract CSS files from CSS.

reference

Interview essentials! The 5 most confusing points in webpack