UNPKG

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