index.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 (targetChunkName) {
  24. const chunkFiles = getChunkFiles(compilation);
  25. /*
  26. Tries to find the target in the chunk files. This is the case
  27. when the chunk is an entrypoint in the webpack config. If it's
  28. not in the chunk files, it is assumed that the target is processed
  29. via a plugin.
  30. */
  31. const assetFileName = chunkFiles.hasOwnProperty(targetChunkName)
  32. ? chunkFiles[targetChunkName]
  33. : targetChunkName;
  34. const targetAsset = assets[assetFileName];
  35. if (!targetAsset) {
  36. console.warn(`the target asset '${targetChunkName}' was not found in the compilation
  37. and therefore gets skipped`.replace(/\s+/g, ' '));
  38. return;
  39. }
  40. const targetSource = String(targetAsset.source());
  41. const modifiedTarget = replaceAssets(targetSource, chunkFiles);
  42. assets[assetFileName] = modifiedTarget
  43. ? createAsset(modifiedTarget, targetChunkName)
  44. : assets[targetAsset];
  45. });
  46. callback();
  47. }.bind(this));
  48. }
  49. };
  50. module.exports = InjectAssetsPlugin;