-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.js
More file actions
73 lines (63 loc) · 2.31 KB
/
index.js
File metadata and controls
73 lines (63 loc) · 2.31 KB
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
'use strict'
var assert = require('assert')
/**
* html webpack preconnect plugin
* @class
*/
function HtmlWebpackPreconnectPlugin(options) {
assert.equal(options, undefined, 'The HtmlWebpackPreconnectPlugin does not accept any options')
}
const addPreconnectLinks = function (htmlPluginData, callback) {
var preconnectedOrigins = htmlPluginData.plugin.options.preconnect;
// we don't need to do nothing if the HtmlWebpackPlugin instance don't have the preconnect option
if (!preconnectedOrigins) {
return callback(null, htmlPluginData);
}
assert.equal(preconnectedOrigins instanceof Array, true, new TypeError('preconnect option needs an array'));
preconnectedOrigins.forEach(function (origin) {
// webpack config may contain quotos, remove that
var href = origin.replace(/['"]+/g, '');
var tag = {
tagName: 'link',
selfClosingTag: false,
attributes: {
rel: 'preconnect',
href: href,
crossorigin: ''
}
};
if (htmlPluginData.head) { // html-webpack-plugin v3
htmlPluginData.head.push(tag);
} else if (htmlPluginData.assetTags) { // html-webpack-plugin v4
htmlPluginData.assetTags.meta.push(tag)
}
});
callback(null, htmlPluginData);
}
HtmlWebpackPreconnectPlugin.prototype.apply = function (compiler) {
// Webpack 4
if (compiler.hooks) {
compiler.hooks.compilation.tap('htmlWebpackPreconnectPlugin', function(compilation) {
// Hook into the html-webpack-plugin processing
var hook
if (typeof compilation.hooks.htmlWebpackPluginAlterAssetTags !== 'undefined') {
hook = compilation.hooks.htmlWebpackPluginAlterAssetTags
} else {
var HtmlWebpackPlugin = require('html-webpack-plugin')
hook = HtmlWebpackPlugin.getHooks(compilation).alterAssetTags
}
if (hook) {
hook.tapAsync('htmlWebpackPreconnectPlugin', addPreconnectLinks)
} else {
console.error('The html-webpack-preconect-plugin not work because it is not compatible with current html-webpack-plugin.')
}
})
// Webpack 3
} else {
compiler.plugin('compilation', function (compilation) {
// Hook into the html-webpack-plugin processing
compilation.plugin('html-webpack-plugin-alter-asset-tags', addPreconnectLinks)
})
}
}
module.exports = HtmlWebpackPreconnectPlugin