From 8d4ceadad1955743ee667ca38e02039e50f40076 Mon Sep 17 00:00:00 2001 From: Jan Nicklas Date: Wed, 6 Jan 2021 17:34:55 +0100 Subject: [PATCH] fix: add support for content hash for light and webapp mode --- src/hash.js | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/hash.js diff --git a/src/hash.js b/src/hash.js new file mode 100644 index 00000000..9324f8ff --- /dev/null +++ b/src/hash.js @@ -0,0 +1,69 @@ +/// @ts-check + +// Import types +/** @typedef {import("webpack").Compilation} WebpackCompilation */ + +const crypto = require('crypto'); +const url = require('url'); + +/** + * Replaces [contenthash] and [fullhash] inside the given publicPath and assetPath + * + * @param {WebpackCompilation} compilation + * @param {undefined | string | Function} publicPath + * @param {string} assetPath + */ +function resolvePublicPath(compilation, publicPath, assetPath) { + const publicPathString = + publicPath && typeof publicPath === 'function' + ? compilation.getAssetPath( + compilation.outputOptions.publicPath || 'auto', + { hash: compilation.hash } + ) + : publicPath; + + const fullAssetPath = url.resolve( + appendSlash(publicPathString || 'auto'), + assetPath + ); + return fullAssetPath; +} + +/** + * Replaces [contenthash] and [fullhash] inside the given publicPath and assetPath + * + * @param {WebpackCompilation} compilation + * @param {string} assetPath + * @param {string} hash + */ +function replaceContentHash(compilation, assetPath, hash) { + return compilation.getAssetPath(assetPath, { + hash: compilation.hash || hash, + chunk: { + id: '1', + hash + }, + contentHash: hash + }); +} + +/** + * Adds a slash to a url + * @param {string} url + */ +function appendSlash(url) { + return url && url.length && url.substr(-1, 1) !== '/' ? url + '/' : url; +} + +/** + * Returns the content hash for the given file content + * @param {Buffer|string} file + */ +function getContentHash(file) { + return crypto + .createHash('sha256') + .update(file.toString('utf8')) + .digest('hex'); +} + +module.exports = { getContentHash, resolvePublicPath, replaceContentHash };