evalSourceMapMiddleware.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /**
  2. * Copyright (c) 2015-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. 'use strict';
  8. function base64SourceMap(source) {
  9. const base64 = Buffer.from(JSON.stringify(source.map()), 'utf8').toString(
  10. 'base64'
  11. );
  12. return `data:application/json;charset=utf-8;base64,${base64}`;
  13. }
  14. function getSourceById(server, id) {
  15. const module = server._stats.compilation.modules.find(m => m.id == id);
  16. return module.originalSource();
  17. }
  18. /*
  19. * Middleware responsible for retrieving a generated source
  20. * Receives a webpack internal url: "webpack-internal:///<module-id>"
  21. * Returns a generated source: "<source-text><sourceMappingURL><sourceURL>"
  22. *
  23. * Based on EvalSourceMapDevToolModuleTemplatePlugin.js
  24. */
  25. module.exports = function createEvalSourceMapMiddleware(server) {
  26. return function handleWebpackInternalMiddleware(req, res, next) {
  27. if (req.url.startsWith('/__get-internal-source')) {
  28. const fileName = req.query.fileName;
  29. const id = fileName.match(/webpack-internal:\/\/\/(.+)/)[1];
  30. if (!id || !server._stats) {
  31. next();
  32. }
  33. const source = getSourceById(server, id);
  34. const sourceMapURL = `//# sourceMappingURL=${base64SourceMap(source)}`;
  35. const sourceURL = `//# sourceURL=webpack-internal:///${module.id}`;
  36. res.end(`${source.source()}\n${sourceMapURL}\n${sourceURL}`);
  37. } else {
  38. next();
  39. }
  40. };
  41. };