-
-
Notifications
You must be signed in to change notification settings - Fork 361
/
setupWriteToDisk.js
81 lines (67 loc) · 2.45 KB
/
setupWriteToDisk.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
const fs = require("fs");
const path = require("path");
/** @typedef {import("webpack").Compiler} Compiler */
/** @typedef {import("webpack").MultiCompiler} MultiCompiler */
/** @typedef {import("webpack").Compilation} Compilation */
/** @typedef {import("../index.js").IncomingMessage} IncomingMessage */
/** @typedef {import("../index.js").ServerResponse} ServerResponse */
/**
* @template {IncomingMessage} Request
* @template {ServerResponse} Response
* @param {import("../index.js").WithOptional<import("../index.js").Context<Request, Response>, "watching" | "outputFileSystem">} context
*/
function setupWriteToDisk(context) {
/**
* @type {Compiler[]}
*/
const compilers =
/** @type {MultiCompiler} */
(context.compiler).compilers || [context.compiler];
for (const compiler of compilers) {
compiler.hooks.emit.tap("DevMiddleware", () => {
// @ts-ignore
if (compiler.hasWebpackDevMiddlewareAssetEmittedCallback) {
return;
}
compiler.hooks.assetEmitted.tapAsync(
"DevMiddleware",
(file, info, callback) => {
const { targetPath, content } = info;
const { writeToDisk: filter } = context.options;
const allowWrite =
filter && typeof filter === "function" ? filter(targetPath) : true;
if (!allowWrite) {
return callback();
}
const dir = path.dirname(targetPath);
const name = compiler.options.name
? `Child "${compiler.options.name}": `
: "";
return fs.mkdir(dir, { recursive: true }, (mkdirError) => {
if (mkdirError) {
context.logger.error(
`${name}Unable to write "${dir}" directory to disk:\n${mkdirError}`,
);
return callback(mkdirError);
}
return fs.writeFile(targetPath, content, (writeFileError) => {
if (writeFileError) {
context.logger.error(
`${name}Unable to write "${targetPath}" asset to disk:\n${writeFileError}`,
);
return callback(writeFileError);
}
context.logger.log(
`${name}Asset written to disk: "${targetPath}"`,
);
return callback();
});
});
},
);
// @ts-ignore
compiler.hasWebpackDevMiddlewareAssetEmittedCallback = true;
});
}
}
module.exports = setupWriteToDisk;