const getChunkFiles = require('./lib/getChunkFiles.js'); const replaceAssets = require('./lib/replaceAssets.js'); const createAsset = require('./lib/createAsset.js'); /** * A webpack plugin which can be used to replace asset names in compiled chunks. * It listens to webpack's emit event and it therefore can also be used in watch mode. * * @param {Object} options - the options for the plugin * @param {string[]} options.targets - the target chunks in which the assets should be replaced * @constructor */ function InjectAssetsPlugin (options = {}) { if (!options.hasOwnProperty('targets')) { throw Error('targets must be specified'); } this.options = options; } InjectAssetsPlugin.prototype = { apply (compiler) { compiler.plugin('emit', function injectAssets(compilation, callback) { const {targets} = this.options; const {assets} = compilation; targets.forEach(function replaceAssetsForTarget (targetAssetName) { const targetAsset = assets[targetAssetName]; if (!targetAsset) { console.warn(`the target asset '${targetAsset}' was not found in the compilation and therefore gets skipped`.replace(/\s+/, ' ')); return; } const chunkFiles = getChunkFiles(compilation); const targetSource = targetAsset.source().toString(); const modifiedTarget = replaceAssets(targetSource, chunkFiles); assets[targetAssetName] = modifiedTarget ? createAsset(modifiedTarget, targetAssetName) : assets[targetAsset]; }); callback(); }.bind(this)); } }; module.exports = InjectAssetsPlugin;