definition of the [contenthash] ?

Can anyone tell me the definition of the [contenthash] which added in webpack@4.3.0 ?

According to the source code, it’s definitely not the the hash of the content(source code or bundle result).

But it should be the hash of the content, just works like extract-text-webpack-plugin. right ?

and why using md4 algorithm while loader-utils using md5 ?

Author: Fantashit

1 thought on “definition of the [contenthash] ?

  1. @z827101859 I can’t tell you why webpack do it this way, but I can show you how webpack do it.

    src/index.js

    console.log('Hello, contenthash')

    webpack.config.js

    module.exports = {
      mode: 'none',
      output: {
        filename: '[name].[contenthash].js'
      },
      optimization: {
        runtimeChunk: true
      }
    }

    First of all, webpack using md4 algorithm to create hash by default.

    const hash = require('crypto').createHash('md4')

    Secondly, I hope you’re already familiar with the concept of Chunk and Module. For this example, we have a main chunk which contain the module src/index.js. Chunk and Module both have the hash property. the good news is, we only need to figure out how module.hash be created, by now.

    how module.hash be created

    module also has a private property called _buildHash, and here is how it be generated.

    hash.update('source')
    hash.update("console.log('Hello, contenthash')") // the source code
    hash.update('meta')
    hash.update('{}') // JSON.stringify(module.buildMeta)
    module._buildHash = hash.digest('hex')

    and the module.hash

    hash.update(module._buildHash)
    hash.update(`${module.id}`)
    hash.update('null')  // JSON.stringify(module.usedExports)
    module.hash = hash.digest('hex')

    Finally, the contenthash

    hash.update('ChunkTemplate')
    hash.update('2')
    hash.update('JsonpChunkTemplatePlugin')
    hash.update('4')
    hash.update('webpackJsonp') // output.jsonpFunction
    hash.update('window') // output.globalObject
    for (const module of chunk.modules) {
      hash.update(module.hash)
    }
    const contenthash = hash.digest('hex').substr(0, hashDigestLength) // by default hashDigestLength equal 20, you can configure by [name].[contenthash:8].js. notice the number 8 ?

Comments are closed.