You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

74 line
2.4 KiB

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