index.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. const getChunkFiles = require('./lib/getChunkFiles.js');
  2. const replaceAssets = require('./lib/replaceAssets.js');
  3. const createAsset = require('./lib/createAsset.js');
  4. const findAsset = require('./lib/findAsset.js');
  5. /**
  6. * A webpack plugin which can be used to replace asset names in compiled chunks.
  7. * It listens to webpack's emit event and it therefore can also be used in watch mode.
  8. *
  9. * @param {Object} options - the options for the plugin
  10. * @param {string[]} options.targets - the target chunks in which the assets should be replaced
  11. * @constructor
  12. */
  13. function InjectAssetsPlugin (options = {}) {
  14. if (!options.hasOwnProperty('targets')) {
  15. throw Error('targets must be specified');
  16. }
  17. this.options = options;
  18. }
  19. InjectAssetsPlugin.prototype = {
  20. apply (compiler) {
  21. compiler.plugin('emit', function injectAssets(compilation, callback) {
  22. const {targets} = this.options;
  23. const {assets} = compilation;
  24. targets.forEach(function replaceAssetsForTarget (targetChunkName) {
  25. const chunkFiles = getChunkFiles(compilation);
  26. /*
  27. Tries to find the target in the chunk files. This is the case
  28. when the chunk is an entrypoint in the webpack config. If it's
  29. not in the chunk files, it is assumed that the target is processed
  30. via a plugin.
  31. */
  32. const assetFileName = chunkFiles.hasOwnProperty(targetChunkName)
  33. ? findAsset(chunkFiles, targetChunkName)
  34. : targetChunkName;
  35. const targetAsset = assets[assetFileName];
  36. if (!targetAsset) {
  37. console.warn(`the target asset '${targetChunkName}' was not found in the compilation
  38. and therefore gets skipped`.replace(/\s+/g, ' '));
  39. return;
  40. }
  41. const targetSource = String(targetAsset.source());
  42. const modifiedTarget = replaceAssets(targetSource, chunkFiles);
  43. assets[assetFileName] = modifiedTarget
  44. ? createAsset(modifiedTarget, targetChunkName)
  45. : assets[targetAsset];
  46. });
  47. callback();
  48. }.bind(this));
  49. }
  50. };
  51. module.exports = InjectAssetsPlugin;