Skip to content

Commit

Permalink
fix: add support for content hash for light and webapp mode
Browse files Browse the repository at this point in the history
  • Loading branch information
jantimon committed Jan 6, 2021
1 parent 8141094 commit 8d4cead
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions src/hash.js
Original file line number Diff line number Diff line change
@@ -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 };

0 comments on commit 8d4cead

Please sign in to comment.