@lipemat/js-boilerplate
Version:
Dependencies and scripts for a no config JavaScript app
71 lines (70 loc) • 2.5 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const node_crypto_1 = __importDefault(require("node:crypto"));
const webpack_1 = require("webpack");
/**
* Webpack plugin for injecting the content hash into
* the manifest.json created by the `webpack-assets-manifest` plugin.
*/
class WebpackAssetsHash {
manifest;
assets = {};
/**
* Pass the same constructed plugin provide to Webpack via
* the `webpack.dist` script.
*/
constructor(manifest) {
this.manifest = manifest;
}
/**
* WebPack plugin entrypoint.
*
* @link https://webpack.js.org/contribute/writing-a-plugin/
*/
apply(compiler) {
this.manifest.hooks.transform.tap('WebpackAssetsHash', this.addHashToManifest.bind(this));
compiler.hooks.thisCompilation.tap('WebpackAssetsHash', compilation => {
compilation.hooks.processAssets.tap({
name: 'WebpackAssetsHash',
stage: webpack_1.Compilation.PROCESS_ASSETS_STAGE_ANALYSE,
}, this.storeContentHash.bind(this, compilation));
});
}
/**
* Store the content hash of each asset in this class, so we
* can inject it into the manifest.json file.
*
* Hash matches Webpack [contenthash].
*/
storeContentHash(compilation) {
for (const asset of compilation.getAssets()) {
this.assets[asset.name] = node_crypto_1.default.createHash('md5')
.update(asset.source.source())
.digest('hex')
.substring(0, 20);
}
}
/**
* Inject the `hash` of the content into the manifest.json
* file generated by webpack-assets-manifest.
*
* @param {Object} assets
*/
addHashToManifest(assets) {
Object.keys(assets).forEach((item) => {
if (item in this.assets && this.assets[item] !== '') {
assets[item].hash = this.assets[item];
}
else if (assets[item].src in this.assets && this.assets[assets[item].src] !== '') {
// If the content hash was added to the asset name before storing.
assets[item].hash = this.assets[assets[item].src];
}
});
return assets;
}
}
module.exports = WebpackAssetsHash;
exports.default = WebpackAssetsHash;