How to save contenthash in webpack configuration
Asked Answered
P

1

8

I previously saved the [hash] value of webpack to a meta.json file:

class MetaInfoPlugin {
  constructor(options) {
    this.options = { filename: 'meta.json', ...options };
  }

  apply(compiler) {
    compiler.hooks.done.tap(this.constructor.name, (stats) => {
      const metaInfo = {
        // add any other information if necessary
        hash: stats.hash
      };
      const json = JSON.stringify(metaInfo);
      return new Promise((resolve, reject) => {
        fs.writeFile(this.options.filename, json, 'utf8', (error) => {
          if (error) {
            reject(error);
            return;
          }
          resolve();
        });
      });
    });
  }
}

module.exports = {
  mode: 'production',
  target: 'web',
...
  plugins: [
    new MetaInfoPlugin({ filename: './public/theme/assets/scripts/meta.json' }),
  ],
...
};

After upgrading to webpack 5 I receive deprecation notices that point to using contenthash or other values instead.

[DEP_WEBPACK_TEMPLATE_PATH_PLUGIN_REPLACE_PATH_VARIABLES_HASH] DeprecationWarning: [hash] is now [fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details)

But exchanging the .hash part above with .contenthash or any of the other hashes won't work. How do I save the contenthash to a file so I can later on use the value in a templating system to so link the file?

What I am basically trying is to get the [contenthash] value into a text file (json, whatever format) to reuse in a PHP templating system later on.

Publea answered 8/11, 2020 at 16:30 Comment(0)
C
6

The deprecation notice is about to use [contenthash] as output filename. Just about:

// ...
output: {
    path: path.resolve(process.cwd(), 'dist'),
    filename: utils.isProd() ? '[name].[contenthash].js' : '[name].js',
    // ...
},

Create filelist.json

Writing the compiled filenames with an own plugin to webpacks output folder:

class FileListPlugin {
    apply(compiler) {
        compiler.hooks.emit.tapAsync('FileListPlugin', (compilation, callback) => {
            var a = { files: [] };

            // build filename array
            for (var filename in compilation.assets) 
                a.files.push(filename);
            
            // build js and css childs
            for (var filename in compilation.assets) {
                var f = filename.split('.');
                var filetype = f[f.length - 1];
                if (filetype === 'css' || filetype === 'js')
                    a[filetype] = {
                        filename: filename,
                        hash: f[f.length - 2]
                    };
            }

            // a to string
            a = JSON.stringify(a);

            // Insert this list into the webpack build as a new file asset:
            compilation.assets['filelist.json'] = {
                source: () => { return a },
                size: () => { return a.length }
            };

            callback();
        });
    }
}

It's a modification from this example https://webpack.js.org/contribute/writing-a-plugin/#example

Register plugin:

plugins: [
    //...
    new FileListPlugin(),
    //...
]

The content of filelist.json looks then like this:

{
    "files": [
        "main.d060b15792a80dc111ee.css",
        "main.0f88c5f5cb783c5a385f.js",
        "layout.pug"
    ],
    "css": {
        "filename": "main.d060b15792a80dc111ee.css",
        "hash": "d060b15792a80dc111ee"
    },
    "js": {
        "filename": "main.0f88c5f5cb783c5a385f.js",
        "hash": "0f88c5f5cb783c5a385f"
    }
}
Cyma answered 21/12, 2020 at 13:43 Comment(2)
I forgot to mark this as right answer, sorry. This solution now started to throw another warning: (node:831376) [DEP_WEBPACK_COMPILATION_ASSETS] DeprecationWarning: Compilation.assets will be frozen in future, all modifications are deprecated. BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation. Do changes to assets earlier, e. g. in Compilation.hooks.processAssets. Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*. This should not apply to this solution as there are no changes?Publea
Have you checked this #64816731Cyma

© 2022 - 2024 — McMap. All rights reserved.