如何在Webpack配置中保存Contenthash

时间:2020-11-08 16:30:09

标签: webpack webpack-5

我以前将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保存到文件,以便以后可以在模板系统中使用该值来链接文件?

我基本上想尝试的是将[contenthash]值转换为文本文件(json,无论何种格式),以便以后在PHP模板系统中重用。

1 个答案:

答案 0 :(得分:2)

弃用通知即将使用 <video-background :src=video style="max-height: 80%; height: 100vh"> 作为输出文件名。差不多:

[contenthash]

创建 filelist.json

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

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

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

注册插件:

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

filelist.json 的内容如下所示:

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