fs.js 2.4 KB

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