1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- const getChunkFiles = require('./lib/getChunkFiles.js');
- const replaceAssets = require('./lib/replaceAssets.js');
- const createAsset = require('./lib/createAsset.js');
- const findAsset = require('./lib/findAsset.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 (targetChunkName) {
- const chunkFiles = getChunkFiles(compilation);
- /*
- Tries to find the target in the chunk files. This is the case
- when the chunk is an entrypoint in the webpack config. If it's
- not in the chunk files, it is assumed that the target is processed
- via a plugin.
- */
- const assetFileName = chunkFiles.hasOwnProperty(targetChunkName)
- ? findAsset(chunkFiles, targetChunkName)
- : targetChunkName;
- const targetAsset = assets[assetFileName];
- if (!targetAsset) {
- console.warn(`the target asset '${targetChunkName}' was not found in the compilation
- and therefore gets skipped`.replace(/\s+/g, ' '));
- return;
- }
- const targetSource = String(targetAsset.source());
- const modifiedTarget = replaceAssets(targetSource, chunkFiles);
- assets[assetFileName] = modifiedTarget
- ? createAsset(modifiedTarget, targetChunkName)
- : assets[targetAsset];
- });
- callback();
- }.bind(this));
- }
- };
- module.exports = InjectAssetsPlugin;
|