-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
70 lines (62 loc) · 1.75 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
"use strict";
const isSvg = require("is-svg");
const imageType = require("image-type");
const SUPPORTED_LINK_TYPES = [
"icon",
"apple-touch-icon",
"apple-touch-startup-image",
];
class InlineIconHtmlPlugin {
constructor(htmlWebpackPlugin, tests) {
this.htmlWebpackPlugin = htmlWebpackPlugin;
this.tests = tests;
}
getInlinedTag(publicPath, assets, tag) {
if (
tag.tagName !== "link" ||
!SUPPORTED_LINK_TYPES.includes(tag.attributes.rel)
) {
return tag;
}
const fileName = publicPath
? tag.attributes.href.replace(publicPath, "")
: tag.attributes.href;
if (!this.tests.some((test) => fileName.match(test))) {
return tag;
}
const asset = assets[fileName];
if (asset == null) {
return tag;
}
let mimeType;
if (isSvg(asset.source())) {
mimeType = "image/svg+xml";
} else {
const fileType = imageType(asset.source());
mimeType = fileType ? fileType.mime : "application/octet-stream";
}
const data = asset.source().toString("base64");
return {
...tag,
attributes: {
...tag.attributes,
href: `data:${mimeType};base64,${data}`,
},
};
}
apply(compiler) {
let publicPath = compiler.options.output.publicPath || "";
if (publicPath && !publicPath.endsWith("/")) {
publicPath += "/";
}
compiler.hooks.compilation.tap("InlineIconHtmlPlugin", (compilation) => {
const hooks = this.htmlWebpackPlugin.getHooks(compilation);
hooks.alterAssetTagGroups.tap("InlineIconHtmlPlugin", (assets) => {
assets.headTags = assets.headTags.map((tag) =>
this.getInlinedTag(publicPath, compilation.assets, tag)
);
});
});
}
}
module.exports = InlineIconHtmlPlugin;