This repository has been archived by the owner on Jan 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 144
/
index.js
149 lines (135 loc) · 5.71 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
/**
* @license
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// See https://github.com/GoogleChromeLabs/preload-webpack-plugin/issues/45
require('object.values').shim();
const objectAssign = require('object-assign');
const flatten = arr => arr.reduce((prev, curr) => prev.concat(curr), []);
const doesChunkBelongToHTML = (chunk, roots, visitedChunks) => {
// Prevent circular recursion.
// See https://github.com/GoogleChromeLabs/preload-webpack-plugin/issues/49
if (visitedChunks[chunk.renderedHash]) {
return false;
}
visitedChunks[chunk.renderedHash] = true;
for (const root of roots) {
if (root.hash === chunk.renderedHash) {
return true;
}
}
for (const parent of chunk.parents) {
if (doesChunkBelongToHTML(parent, roots, visitedChunks)) {
return true;
}
}
return false;
};
const defaultOptions = {
rel: 'preload',
include: 'asyncChunks',
fileBlacklist: [/\.map/],
excludeHtmlNames: [],
};
class PreloadPlugin {
constructor(options) {
this.options = objectAssign({}, defaultOptions, options);
}
apply(compiler) {
const options = this.options;
compiler.plugin('compilation', compilation => {
compilation.plugin('html-webpack-plugin-before-html-processing', (htmlPluginData, cb) => {
if (this.options.excludeHtmlNames.indexOf(htmlPluginData.plugin.options.filename) > -1) {
cb(null, htmlPluginData);
return;
}
let filesToInclude = '';
let extractedChunks = [];
// 'asyncChunks' are chunks intended for lazy/async loading usually generated as
// part of code-splitting with import() or require.ensure(). By default, asyncChunks
// get wired up using link rel=preload when using this plugin. This behaviour can be
// configured to preload all types of chunks or just prefetch chunks as needed.
if (options.include === undefined || options.include === 'asyncChunks') {
try {
extractedChunks = compilation.chunks.filter(chunk => !chunk.isInitial());
} catch (e) {
extractedChunks = compilation.chunks;
}
} else if (options.include === 'initial') {
try {
extractedChunks = compilation.chunks.filter(chunk => chunk.isInitial());
} catch (e) {
extractedChunks = compilation.chunks;
}
} else if (options.include === 'all') {
// Async chunks, vendor chunks, normal chunks.
extractedChunks = compilation.chunks;
} else if (Array.isArray(options.include)) {
// Keep only user specified chunks
extractedChunks = compilation
.chunks
.filter((chunk) => {
const chunkName = chunk.name;
// Works only for named chunks
if (!chunkName) {
return false;
}
return options.include.indexOf(chunkName) > -1;
});
}
const publicPath = compilation.outputOptions.publicPath || '';
// Only handle the chunk import by the htmlWebpackPlugin
extractedChunks = extractedChunks.filter(chunk => doesChunkBelongToHTML(
chunk, Object.values(htmlPluginData.assets.chunks), {}));
flatten(extractedChunks.map(chunk => chunk.files)).filter(entry => {
return this.options.fileBlacklist.every(regex => regex.test(entry) === false);
}).forEach(entry => {
entry = `${publicPath}${entry}`;
if (options.rel === 'preload') {
// If `as` value is not provided in option, dynamically determine the correct
// value depends on suffix of filename. Otherwise use the given `as` value.
let asValue;
if (!options.as) {
if (entry.match(/\.css$/)) asValue = 'style';
else if (entry.match(/\.woff2$/)) asValue = 'font';
else asValue = 'script';
} else if (typeof options.as === 'function') {
asValue = options.as(entry);
} else {
asValue = options.as;
}
const crossOrigin = asValue === 'font' ? 'crossorigin="crossorigin" ' : '';
filesToInclude+= `<link rel="${options.rel}" as="${asValue}" ${crossOrigin}href="${entry}">\n`;
} else {
// If preload isn't specified, the only other valid entry is prefetch here
// You could specify preconnect but as we're dealing with direct paths to resources
// instead of origins that would make less sense.
filesToInclude+= `<link rel="${options.rel}" href="${entry}">\n`;
}
});
if (htmlPluginData.html.indexOf('</head>') !== -1) {
// If a valid closing </head> is found, update it to include preload/prefetch tags
htmlPluginData.html = htmlPluginData.html.replace('</head>', filesToInclude + '</head>');
} else {
// Otherwise assume at least a <body> is present and update it to include a new <head>
htmlPluginData.html = htmlPluginData.html.replace('<body>', '<head>' + filesToInclude + '</head><body>');
}
cb(null, htmlPluginData);
});
});
}
}
module.exports = PreloadPlugin;