/
trusted-types-html-generator-plugin.js
82 lines (76 loc) · 2.13 KB
/
trusted-types-html-generator-plugin.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
82
"use strict";
const HTMLContentForIndex = `
<!DOCTYPE html>
<html>
<head>
<meta
http-equiv="Content-Security-Policy"
content="require-trusted-types-for 'script'; trusted-types webpack webpack#dev-overlay;"
/>
<meta charset='UTF-8'>
<title>webpack-dev-server</title>
</head>
<body>
<h1>webpack-dev-server is running...</h1>
<script type="text/javascript" charset="utf-8" src="/main.js"></script>
</body>
</html>
`;
const HTMLContentForTest = `
<!DOCTYPE html>
<html>
<head>
<meta
http-equiv="Content-Security-Policy"
content="require-trusted-types-for 'script'; trusted-types webpack webpack#dev-overlay;"
/>
<meta charset='UTF-8'>
<title>test</title>
</head>
<body>
<h1>Created via HTMLGeneratorPlugin</h1>
</body>
</html>
`;
module.exports = class HTMLGeneratorPlugin {
// eslint-disable-next-line class-methods-use-this
apply(compiler) {
const pluginName = "html-generator-plugin";
compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
if (compiler.webpack) {
const { RawSource } = compiler.webpack.sources;
compilation.hooks.processAssets.tap(
{
name: pluginName,
stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
},
() => {
const indexSource = new RawSource(HTMLContentForIndex);
const testSource = new RawSource(HTMLContentForTest);
compilation.emitAsset("index.html", indexSource);
compilation.emitAsset("test.html", testSource);
}
);
} else {
compilation.hooks.additionalAssets.tap(pluginName, () => {
compilation.emitAsset("index.html", {
source() {
return HTMLContentForIndex;
},
size() {
return HTMLContentForIndex.length;
},
});
compilation.emitAsset("test.html", {
source() {
return HTMLContentForTest;
},
size() {
return HTMLContentForTest.length;
},
});
});
}
});
}
};