|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const fs = require('fs'); |
| 4 | +const path = require('path'); |
| 5 | +const chalk = require('chalk'); // eslint-disable-line import/no-extraneous-dependencies |
| 6 | +const MemoryFileSystem = require('memory-fs'); |
| 7 | +const pathabs = require('path-is-absolute'); |
| 8 | +const NodeOutputFileSystem = require('webpack/lib/node/NodeOutputFileSystem'); |
| 9 | +const DevMiddlewareError = require('./DevMiddlewareError'); |
| 10 | + |
| 11 | +const { mkdirp } = new NodeOutputFileSystem(); |
| 12 | + |
| 13 | +module.exports = { |
| 14 | + toDisk(context) { |
| 15 | + context.compiler.hooks.afterEmit.tap('WebpackDevMiddleware', (compilation) => { |
| 16 | + const { assets, compiler } = compilation; |
| 17 | + const { log } = context; |
| 18 | + const { writeToDisk: filter } = context.options; |
| 19 | + let { outputPath } = compiler; |
| 20 | + |
| 21 | + if (outputPath === '/') { |
| 22 | + outputPath = compiler.context; |
| 23 | + } |
| 24 | + |
| 25 | + for (const assetPath of Object.keys(assets)) { |
| 26 | + const asset = assets[assetPath]; |
| 27 | + const source = asset.source(); |
| 28 | + const isAbsolute = pathabs(assetPath); |
| 29 | + const writePath = isAbsolute ? assetPath : path.join(outputPath, assetPath); |
| 30 | + const relativePath = path.relative(process.cwd(), writePath); |
| 31 | + const allowWrite = filter && typeof filter === 'function' ? filter(writePath) : true; |
| 32 | + |
| 33 | + if (allowWrite) { |
| 34 | + let output = source; |
| 35 | + |
| 36 | + mkdirp.sync(path.dirname(writePath)); |
| 37 | + |
| 38 | + if (Array.isArray(source)) { |
| 39 | + output = source.join('\n'); |
| 40 | + } |
| 41 | + |
| 42 | + try { |
| 43 | + fs.writeFileSync(writePath, output, 'utf-8'); |
| 44 | + log.debug(chalk`{cyan Asset written to disk}: ${relativePath}`); |
| 45 | + } catch (e) { |
| 46 | + log.error(`Unable to write asset to disk:\n${e}`); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + }); |
| 51 | + }, |
| 52 | + |
| 53 | + setFs(context, compiler) { |
| 54 | + if (typeof compiler.outputPath === 'string' && !pathabs.posix(compiler.outputPath) && !pathabs.win32(compiler.outputPath)) { |
| 55 | + throw new DevMiddlewareError('`output.path` needs to be an absolute path or `/`.'); |
| 56 | + } |
| 57 | + |
| 58 | + let fileSystem; |
| 59 | + // store our files in memory |
| 60 | + const isMemoryFs = !compiler.compilers && compiler.outputFileSystem instanceof MemoryFileSystem; |
| 61 | + |
| 62 | + if (isMemoryFs) { |
| 63 | + fileSystem = compiler.outputFileSystem; |
| 64 | + } else { |
| 65 | + fileSystem = new MemoryFileSystem(); |
| 66 | + compiler.outputFileSystem = fileSystem; |
| 67 | + } |
| 68 | + |
| 69 | + context.fs = fileSystem; |
| 70 | + } |
| 71 | +}; |
0 commit comments