-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathHtmlInlineScriptPlugin.ts
More file actions
145 lines (116 loc) · 4.3 KB
/
HtmlInlineScriptPlugin.ts
File metadata and controls
145 lines (116 loc) · 4.3 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import { Compilation } from 'webpack';
import type { Compiler, WebpackPluginInstance } from 'webpack';
import htmlWebpackPlugin from 'html-webpack-plugin';
import type { HtmlTagObject } from 'html-webpack-plugin';
import { PLUGIN_PREFIX } from './constants';
export type PluginOptions = {
scriptMatchPattern?: RegExp[];
htmlMatchPattern?: RegExp[];
assetPreservePattern?: RegExp[];
};
class HtmlInlineScriptPlugin implements WebpackPluginInstance {
scriptMatchPattern: NonNullable<PluginOptions['scriptMatchPattern']>;
htmlMatchPattern: NonNullable<PluginOptions['htmlMatchPattern']>;
processedScriptFiles: string[];
ignoredHtmlFiles: string[];
assetPreservePattern: NonNullable<PluginOptions['assetPreservePattern']>;
constructor(options: PluginOptions = {}) {
if (options && Array.isArray(options)) {
// eslint-disable-next-line no-console
console.error(
'\x1b[35m%s \x1b[31m%s %s\x1b[0m',
'[html-inline-script-webpack-plugin]',
'Options is now an object containing `scriptMatchPattern` and `htmlMatchPattern` in version 3.x.',
'Please refer to documentation for more information.'
);
throw new Error('OPTIONS_PATTERN_UNMATCHED');
}
const {
scriptMatchPattern = [/.+[.]js$/],
htmlMatchPattern = [/.+[.]html$/],
assetPreservePattern = [],
} = options;
this.scriptMatchPattern = scriptMatchPattern;
this.htmlMatchPattern = htmlMatchPattern;
this.processedScriptFiles = [];
this.assetPreservePattern = assetPreservePattern;
this.ignoredHtmlFiles = [];
}
isFileNeedsToBeInlined(
assetName: string
): boolean {
return this.scriptMatchPattern.some((test) => assetName.match(test));
}
isFileNeedsToBePreserved(
assetName: string
): boolean {
return this.assetPreservePattern.some((test) => assetName.match(test));
}
shouldProcessHtml(
templateName: string
): boolean {
return this.htmlMatchPattern.some((test) => templateName.match(test));
}
processScriptTag(
publicPath: string,
assets: Compilation['assets'],
tag: HtmlTagObject
): HtmlTagObject {
if (tag.tagName !== 'script' || !tag.attributes?.src) {
return tag;
}
// Decoded is needed for special characters in filename like '@' since they will be escaped
const scriptName = decodeURIComponent((tag.attributes.src as string).replace(publicPath, ''));
if (!this.isFileNeedsToBeInlined(scriptName)) {
return tag;
}
const asset = assets[scriptName];
if (!asset) {
return tag;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { src, ...attributesWithoutSrc } = tag.attributes;
this.processedScriptFiles.push(scriptName);
return {
tagName: 'script',
// escape '</script>' appears in source
innerHTML: (asset.source() as string).replace(/(<)(\/script>)/g, '\\x3C$2'),
voidTag: false,
attributes: attributesWithoutSrc,
meta: { plugin: 'html-inline-script-webpack-plugin' }
};
}
apply(compiler: Compiler): void {
let publicPath = compiler.options?.output?.publicPath as string || '';
if (publicPath && !publicPath.endsWith('/')) {
publicPath += '/';
}
compiler.hooks.compilation.tap(`${PLUGIN_PREFIX}_compilation`, (compilation) => {
const hooks = htmlWebpackPlugin.getHooks(compilation);
hooks.alterAssetTags.tap(`${PLUGIN_PREFIX}_alterAssetTags`, (data) => {
const htmlFileName = data.plugin.options?.filename;
if (htmlFileName && !this.shouldProcessHtml(htmlFileName)) {
this.ignoredHtmlFiles.push(htmlFileName);
return data;
}
data.assetTags.scripts = data.assetTags.scripts.map(
(tag: HtmlTagObject) => this.processScriptTag(publicPath, compilation.assets, tag)
);
return data;
});
compilation.hooks.processAssets.tap({
name: `${PLUGIN_PREFIX}_PROCESS_ASSETS_STAGE_SUMMARIZE`,
stage: Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE
}, (assets) => {
if (this.ignoredHtmlFiles.length === 0) {
this.processedScriptFiles.forEach((assetName) => {
if (!this.isFileNeedsToBePreserved(assetName)) {
delete assets[assetName];
}
});
}
});
});
}
}
export default HtmlInlineScriptPlugin;