-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathhtml-generator-plugin.js
More file actions
85 lines (77 loc) · 2.25 KB
/
html-generator-plugin.js
File metadata and controls
85 lines (77 loc) · 2.25 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
const HTMLContentForIndex = (styleTags = '') => `
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>rspack-dev-server</title>
${styleTags}
</head>
<body>
<h1>rspack-dev-server is running...</h1>
<script type="text/javascript" charset="utf-8" src="/main.js"></script>
</body>
</html>
`;
const HTMLContentForAssets = (assetName) => `
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>rspack-dev-server</title>
</head>
<body>
<h1>(${assetName}>)rspack-dev-server is running...</h1>
<script type="text/javascript" charset="utf-8" src=${assetName}></script>
</body>
</html>
`;
const HTMLContentForTest = `
<!DOCTYPE html>
<html>
<head>
<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) => {
const { RawSource } = compiler.rspack.sources;
compilation.hooks.processAssets.tap(
{
name: pluginName,
stage: compiler.rspack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
},
() => {
const testSource = new RawSource(HTMLContentForTest);
const assets = compilation.getAssets();
const styleTags = assets
.filter((asset) => asset.name.endsWith('.css'))
.map((asset) => `<link rel="stylesheet" href="/${asset.name}" />`)
.join('\n ');
const indexSource = new RawSource(HTMLContentForIndex(styleTags));
compilation.emitAsset('index.html', indexSource);
compilation.emitAsset('test.html', testSource);
for (const asset of assets) {
const assetName = asset.name;
if (assetName !== 'main.js' && assetName.endsWith('.js')) {
const assetSource = new RawSource(
HTMLContentForAssets(assetName),
);
compilation.emitAsset(
assetName.replace('.js', '.html'),
assetSource,
);
}
}
},
);
});
}
};