-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathindex.js
More file actions
31 lines (27 loc) · 1.08 KB
/
index.js
File metadata and controls
31 lines (27 loc) · 1.08 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
const HtmlWebpackPlugin = require('html-webpack-plugin');
export class BaseHrefWebpackPlugin {
constructor(options) {
this.options = options;
}
apply(compiler) {
if (!this.options.baseHref) {
return;
}
compiler.hooks.compilation.tap('BaseHrefWebpackPlugin', (compilation) => {
HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync('BaseHrefWebpackPlugin', (data, callback) => {
// Check if base tag already exists
const baseTagRegex = /<base.*?>/i;
const baseTagMatches = data.html.match(baseTagRegex);
if (!baseTagMatches) {
// Insert it in top of the head
data.html = data.html.replace(/<head>/i, '$&' + `<base href="${this.options.baseHref}">`);
} else {
// Otherwise replace href attribute of current base tag
const modifiedBaseTag = baseTagMatches[0].replace(/href="\S+"/i, `href="${this.options.baseHref}"`);
data.html = data.html.replace(baseTagRegex, modifiedBaseTag);
}
callback(null, data);
});
});
}
}