'In Webpack, how do I generate a content hash for only some files?

Webpack has a caching mechanism:

https://webpack.js.org/guides/caching/

That allows you to generate a content hash for your JS files.

Suppose I'm building many JS files and I only want to use the content hash for one of them.

How do I do this in webpack?



Solution 1:[1]

You mean something like this =>

const productionConfig = merge([  
 {
   output: {
      chunkFilename: "[name].[contenthash].js",
      filename: "[name].[contenthash].js",
      assetModuleFilename: "[name].[contenthash][ext][query]",
    },  
 },

  ... ])

These variables are Placeholders in webpack:

[id] - Returns the chunk id.

[path] - Returns the file path.

[name] - Returns the file name.

[ext] - Returns the extension. [ext] works for most available fields.

[fullhash] - Returns the build hash. If any portion of the build changes, this changes as well.

[chunkhash] - Returns an entry chunk-specific hash. Each entry defined in the configuration receives a hash of its own. If any portion of the entry changes, the hash will change as well. [chunkhash] is more granular than [fullhash] by definition.

[contenthash] - Returns a hash generated based on content. It's the new default in production mode starting from webpack 5.

It's preferable to use particularly hash and contenthash only for production purposes as hashing doesn't do much good during development.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1