This repository has been archived by the owner on Nov 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
81 lines (74 loc) · 2.44 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
// eslint-disable-next-line import/no-unresolved
const HtmlWebpackPlugin = require('html-webpack-plugin');
const PLUGIN_NAME = 'HtmlWebpackTransformPlugin';
const handleAssetPath = (assetPath, publicPath, pathPrefix, replace) => {
if (!(replace && assetPath.indexOf(publicPath) === 0)) {
return `${pathPrefix}${assetPath}`;
}
return `${pathPrefix}${assetPath.substring(publicPath.length)}`;
};
const updateTags = ({
attributes: additional, tags, prefix, publicPath, replace, transform,
}) => tags.map(({ attributes, tagName, ...tag }) => ({
...tag,
attributes: {
...attributes,
...(attributes.src
? {
src: handleAssetPath(attributes.src, publicPath, prefix, replace),
}
: {}),
...(attributes.href
? {
href: handleAssetPath(attributes.href, publicPath, prefix, replace),
}
: {}),
...(additional && additional[tagName] ? additional[tagName] : {}),
},
tagName,
})).map(transform);
class Plugin {
constructor(options) {
this.options = options;
}
apply(compiler) {
const {
attributes = {},
pathPrefix: prefix = '',
transform = (tag) => tag,
replacePublicPath: replace = false,
} = this.options;
if (HtmlWebpackPlugin.getHooks) {
// HtmlWebpackPlugin version 4.0.0-beta.5
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const { publicPath } = compilation.outputOptions;
HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tapAsync(
PLUGIN_NAME,
(data, callback) => {
data.headTags = updateTags({
tags: data.headTags, prefix, publicPath, replace, attributes, transform,
});
data.bodyTags = updateTags({
tags: data.bodyTags, prefix, publicPath, replace, attributes, transform,
});
callback(null, data);
},
);
});
} else {
// HtmlWebpackPlugin version 3.2.0
compiler.plugin('compilation', (compilation) => {
const { publicPath } = compilation.outputOptions;
compilation.plugin('html-webpack-plugin-alter-asset-tags', (data) => {
data.head = updateTags({
tags: data.head, prefix, publicPath, replace, attributes, transform,
});
data.body = updateTags({
tags: data.body, prefix, publicPath, replace, attributes, transform,
});
});
});
}
}
}
module.exports = Plugin;