generated from vivid-lapin/ts
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPostProcessPlugin.ts
47 lines (45 loc) · 1.81 KB
/
PostProcessPlugin.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
import fs from "fs"
import path from "path"
export default class PostProcessPlugin {
public readonly name = "PostProcessPlugin"
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public apply(compiler: any) {
compiler.hooks.done.tapAsync(
this.name,
async (
stats: { compilation: { assets: Record<string, {}> } },
callback: Function
) => {
for (const assetName of Object.keys(stats.compilation.assets)) {
if (!assetName.endsWith(".licenses.txt")) {
continue
}
const existsAt = path.join(path.resolve("./dist"), assetName)
if (!fs.existsSync(existsAt)) {
continue
}
const bundlePath = existsAt.replace(".licenses.txt", ".js")
console.info(`${existsAt} -> ${bundlePath}`)
const bundle = await fs.promises.readFile(bundlePath, "utf8")
const license = await fs.promises.readFile(existsAt, "utf8")
const version = bundle.match(/version: "(\d+\.\d+\.\d+)"/)?.[1]
const newBundle = `/*! ${assetName.replace(".licenses.txt", "")}${
version ? ` ${version}` : ""
} */\n/*!\n${license}\n*/\n${bundle}`
.replace(
`import{createRequire as __WEBPACK_EXTERNAL_createRequire}from"module";`,
"const __WEBPACK_EXTERNAL_createRequire = () => (s) => require(s);"
)
.replace(/import\.meta\.url/g, "undefined")
.replace(
'__WEBPACK_EXTERNAL_createRequire(n.url)("fs")',
'{...__WEBPACK_EXTERNAL_createRequire(n.url)("fs"),ReadStream:class ReadStream{},WriteStream:class WriteStream{}}'
)
await fs.promises.writeFile(bundlePath, newBundle)
await fs.promises.unlink(existsAt)
}
callback()
}
)
}
}