如何在 webpack 配置中保存 contenthash

How to save contenthash in webpack configuration

我之前将webpack的[hash]值保存到一个meta.json文件中:

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' }),
  ],
...
};

升级到 webpack 5 后,我收到弃用通知,指出改为使用 contenthash 或其他值。

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

但是将上面的 .hash 部分与 .contenthash 或任何其他哈希值交换将不起作用。如何将 contenthash 保存到文件中,以便以后可以使用模板系统中的值来 link 文件?

我主要尝试的是将 [contenthash] 值放入文本文件(json,任何格式),以便稍后在 PHP 模板系统中重用。

弃用通知即将使用 [contenthash] 作为输出文件名。刚好:

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

创建filelist.json

使用自己的插件将编译后的文件名写入 webpacks 输出文件夹:

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();
        });
    }
}

这是对这个例子的修改https://webpack.js.org/contribute/writing-a-plugin/#example

注册插件:

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

filelist.json 的内容如下所示:

{
    "files": [
        "main.d060b15792a80dc111ee.css",
        "main.0f88c5f5cb783c5a385f.js",
        "layout.pug"
    ],
    "css": {
        "filename": "main.d060b15792a80dc111ee.css",
        "hash": "d060b15792a80dc111ee"
    },
    "js": {
        "filename": "main.0f88c5f5cb783c5a385f.js",
        "hash": "0f88c5f5cb783c5a385f"
    }
}