InlineChunkHtmlPlugin.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * Copyright (c) 2015-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. 'use strict';
  8. class InlineChunkHtmlPlugin {
  9. constructor(htmlWebpackPlugin, tests) {
  10. this.htmlWebpackPlugin = htmlWebpackPlugin;
  11. this.tests = tests;
  12. }
  13. getInlinedTag(publicPath, assets, tag) {
  14. if (tag.tagName !== 'script' || !(tag.attributes && tag.attributes.src)) {
  15. return tag;
  16. }
  17. const scriptName = publicPath
  18. ? tag.attributes.src.replace(publicPath, '')
  19. : tag.attributes.src;
  20. if (!this.tests.some(test => scriptName.match(test))) {
  21. return tag;
  22. }
  23. const asset = assets[scriptName];
  24. if (asset == null) {
  25. return tag;
  26. }
  27. return { tagName: 'script', innerHTML: asset.source(), closeTag: true };
  28. }
  29. apply(compiler) {
  30. let publicPath = compiler.options.output.publicPath || '';
  31. if (publicPath && !publicPath.endsWith('/')) {
  32. publicPath += '/';
  33. }
  34. compiler.hooks.compilation.tap('InlineChunkHtmlPlugin', compilation => {
  35. const tagFunction = tag =>
  36. this.getInlinedTag(publicPath, compilation.assets, tag);
  37. const hooks = this.htmlWebpackPlugin.getHooks(compilation);
  38. hooks.alterAssetTagGroups.tap('InlineChunkHtmlPlugin', assets => {
  39. assets.headTags = assets.headTags.map(tagFunction);
  40. assets.bodyTags = assets.bodyTags.map(tagFunction);
  41. });
  42. // Still emit the runtime chunk for users who do not use our generated
  43. // index.html file.
  44. // hooks.afterEmit.tap('InlineChunkHtmlPlugin', () => {
  45. // Object.keys(compilation.assets).forEach(assetName => {
  46. // if (this.tests.some(test => assetName.match(test))) {
  47. // delete compilation.assets[assetName];
  48. // }
  49. // });
  50. // });
  51. });
  52. }
  53. }
  54. module.exports = InlineChunkHtmlPlugin;