index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. const getChunkFiles = require('./lib/getChunkFiles.js');
  2. const replaceAssets = require('./lib/replaceAssets.js');
  3. const createAsset = require('./lib/createAsset.js');
  4. /**
  5. * A webpack plugin which can be used to replace asset names in compiled chunks.
  6. * It listens to webpack's emit event and it therefore can also be used in watch mode.
  7. *
  8. * @param {Object} options - the options for the plugin
  9. * @param {string[]} options.targets - the target chunks in which the assets should be replaced
  10. * @constructor
  11. */
  12. function InjectAssetsPlugin (options = {}) {
  13. if (!options.hasOwnProperty('targets')) {
  14. throw Error('targets must be specified');
  15. }
  16. this.options = options;
  17. }
  18. InjectAssetsPlugin.prototype = {
  19. apply (compiler) {
  20. compiler.plugin('emit', function injectAssets(compilation, callback) {
  21. const {targets} = this.options;
  22. const {assets} = compilation;
  23. targets.forEach(function replaceAssetsForTarget (targetAssetName) {
  24. const targetAsset = assets[targetAssetName];
  25. if (!targetAsset) {
  26. console.warn(`the target asset '${targetAsset}' was not found in the compilation
  27. and therefore gets skipped`.replace(/\s+/, ' '));
  28. return;
  29. }
  30. const chunkFiles = getChunkFiles(compilation);
  31. const targetSource = targetAsset.source().toString();
  32. const modifiedTarget = replaceAssets(targetSource, chunkFiles);
  33. assets[targetAssetName] = modifiedTarget
  34. ? createAsset(modifiedTarget, targetAssetName)
  35. : assets[targetAsset];
  36. });
  37. callback();
  38. }.bind(this));
  39. }
  40. };
  41. module.exports = InjectAssetsPlugin;