You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

61 lines
1.8 KiB

  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 = tag.attributes.src.replace(publicPath, '');
  18. if (!this.tests.some(test => scriptName.match(test))) {
  19. return tag;
  20. }
  21. const asset = assets[scriptName];
  22. if (asset == null) {
  23. return tag;
  24. }
  25. return { tagName: 'script', innerHTML: asset.source(), closeTag: true };
  26. }
  27. apply(compiler) {
  28. let publicPath = compiler.options.output.publicPath;
  29. if (!publicPath.endsWith('/')) {
  30. publicPath += '/';
  31. }
  32. compiler.hooks.compilation.tap('InlineChunkHtmlPlugin', compilation => {
  33. const tagFunction = tag =>
  34. this.getInlinedTag(publicPath, compilation.assets, tag);
  35. const hooks = this.htmlWebpackPlugin.getHooks(compilation);
  36. hooks.alterAssetTagGroups.tap('InlineChunkHtmlPlugin', assets => {
  37. assets.headTags = assets.headTags.map(tagFunction);
  38. assets.bodyTags = assets.bodyTags.map(tagFunction);
  39. });
  40. // Still emit the runtime chunk for users who do not use our generated
  41. // index.html file.
  42. // hooks.afterEmit.tap('InlineChunkHtmlPlugin', () => {
  43. // Object.keys(compilation.assets).forEach(assetName => {
  44. // if (this.tests.some(test => assetName.match(test))) {
  45. // delete compilation.assets[assetName];
  46. // }
  47. // });
  48. // });
  49. });
  50. }
  51. }
  52. module.exports = InlineChunkHtmlPlugin;