-
-
Notifications
You must be signed in to change notification settings - Fork 361
/
fs.js
77 lines (64 loc) · 2.55 KB
/
fs.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
'use strict';
const fs = require('fs');
const path = require('path');
const { fs: memfs } = require('memfs');
// borrow join and normalize from memory-fs
memfs.join = require('memory-fs/lib/join');
memfs.normalize = require('memory-fs/lib/normalize');
const { colors } = require('webpack-log');
const NodeOutputFileSystem = require('webpack/lib/node/NodeOutputFileSystem');
const DevMiddlewareError = require('./DevMiddlewareError');
const { mkdirp } = new NodeOutputFileSystem();
module.exports = {
toDisk(context) {
const compilers = context.compiler.compilers || [context.compiler];
for (const compiler of compilers) {
compiler.hooks.afterEmit.tap('WebpackDevMiddleware', (compilation) => {
const { assets } = compilation;
const { log } = context;
const { writeToDisk: filter } = context.options;
let { outputPath } = compiler;
if (outputPath === '/') {
outputPath = compiler.context;
}
for (const assetPath of Object.keys(assets)) {
const asset = assets[assetPath];
const source = asset.source();
const [assetPathClean] = assetPath.split('?');
const isAbsolute = path.isAbsolute(assetPathClean);
const writePath = isAbsolute ? assetPathClean : path.join(outputPath, assetPathClean);
const relativePath = path.relative(process.cwd(), writePath);
const allowWrite = filter && typeof filter === 'function' ? filter(writePath) : true;
if (allowWrite) {
let output = source;
mkdirp.sync(path.dirname(writePath));
if (Array.isArray(source)) {
output = source.join('\n');
}
try {
fs.writeFileSync(writePath, output, 'utf-8');
log.debug(colors.cyan(`Asset written to disk: ${relativePath}`));
} catch (e) {
log.error(`Unable to write asset to disk:\n${e}`);
}
}
}
});
}
},
setFs(context, compiler) {
if (typeof compiler.outputPath === 'string' && !path.posix.isAbsolute(compiler.outputPath) && !path.win32.isAbsolute(compiler.outputPath)) {
throw new DevMiddlewareError('`output.path` needs to be an absolute path or `/`.');
}
let fileSystem;
// store our files in memory
const isMemoryFs = !compiler.compilers && compiler.outputFileSystem === memfs;
if (isMemoryFs) {
fileSystem = compiler.outputFileSystem;
} else {
fileSystem = memfs;
compiler.outputFileSystem = fileSystem;
}
context.fs = fileSystem;
}
};