setupWriteToDisk.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = setupWriteToDisk;
  6. var _fs = _interopRequireDefault(require("fs"));
  7. var _path = _interopRequireDefault(require("path"));
  8. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9. function setupWriteToDisk(context) {
  10. const compilers = context.compiler.compilers || [context.compiler];
  11. for (const compiler of compilers) {
  12. compiler.hooks.emit.tap("DevMiddleware", compilation => {
  13. if (compiler.hasWebpackDevMiddlewareAssetEmittedCallback) {
  14. return;
  15. }
  16. compiler.hooks.assetEmitted.tapAsync("DevMiddleware", (file, info, callback) => {
  17. let targetPath = null;
  18. let content = null; // webpack@5
  19. if (info.compilation) {
  20. ({
  21. targetPath,
  22. content
  23. } = info);
  24. } else {
  25. let targetFile = file;
  26. const queryStringIdx = targetFile.indexOf("?");
  27. if (queryStringIdx >= 0) {
  28. targetFile = targetFile.substr(0, queryStringIdx);
  29. }
  30. let {
  31. outputPath
  32. } = compiler;
  33. outputPath = compilation.getPath(outputPath, {});
  34. content = info;
  35. targetPath = _path.default.join(outputPath, targetFile);
  36. }
  37. const {
  38. writeToDisk: filter
  39. } = context.options;
  40. const allowWrite = filter && typeof filter === "function" ? filter(targetPath) : true;
  41. if (!allowWrite) {
  42. return callback();
  43. }
  44. const dir = _path.default.dirname(targetPath);
  45. const name = compiler.options.name ? `Child "${compiler.options.name}": ` : "";
  46. return _fs.default.mkdir(dir, {
  47. recursive: true
  48. }, mkdirError => {
  49. if (mkdirError) {
  50. context.logger.error(`${name}Unable to write "${dir}" directory to disk:\n${mkdirError}`);
  51. return callback(mkdirError);
  52. }
  53. return _fs.default.writeFile(targetPath, content, writeFileError => {
  54. if (writeFileError) {
  55. context.logger.error(`${name}Unable to write "${targetPath}" asset to disk:\n${writeFileError}`);
  56. return callback(writeFileError);
  57. }
  58. context.logger.log(`${name}Asset written to disk: "${targetPath}"`);
  59. return callback();
  60. });
  61. });
  62. });
  63. compiler.hasWebpackDevMiddlewareAssetEmittedCallback = true;
  64. });
  65. }
  66. }