-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathbase-href-webpack-plugin.ts
49 lines (44 loc) · 1.58 KB
/
base-href-webpack-plugin.ts
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
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// tslint:disable
// TODO: cleanup this file, it's copied as is from Angular CLI.
export interface BaseHrefWebpackPluginOptions {
baseHref: string;
}
export class BaseHrefWebpackPlugin {
constructor(public readonly options: BaseHrefWebpackPluginOptions) { }
apply(compiler: any): void {
// Ignore if baseHref is not passed
if (!this.options.baseHref && this.options.baseHref !== '') {
return;
}
compiler.plugin('compilation', (compilation: any) => {
compilation.plugin(
'html-webpack-plugin-before-html-processing',
(htmlPluginData: any, callback: Function) => {
// Check if base tag already exists
const baseTagRegex = /<base.*?>/i;
const baseTagMatches = htmlPluginData.html.match(baseTagRegex);
if (!baseTagMatches) {
// Insert it in top of the head if not exist
htmlPluginData.html = htmlPluginData.html.replace(
/<head>/i, '$&' + `<base href="${this.options.baseHref}">`
);
} else {
// Replace only href attribute if exists
const modifiedBaseTag = baseTagMatches[0].replace(
/href="\S*?"/i, `href="${this.options.baseHref}"`
);
htmlPluginData.html = htmlPluginData.html.replace(baseTagRegex, modifiedBaseTag);
}
callback(null, htmlPluginData);
}
);
});
}
}