sourcemap.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.uniPostSourceMapPlugin = void 0;
  4. const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
  5. const path_1 = require("path");
  6. function uniPostSourceMapPlugin() {
  7. return {
  8. name: 'uni:post-sourcemap',
  9. apply: 'serve',
  10. enforce: 'post',
  11. configureServer(server) {
  12. // cli 工程呢?
  13. // 重要:hack 了 _pendingRequests,来修改 map
  14. const pendingRequests = new PendingRequests();
  15. pendingRequests._server = server;
  16. pendingRequests._inputDir = (0, uni_cli_shared_1.normalizePath)(process.env.UNI_INPUT_DIR);
  17. // @ts-expect-error
  18. server._pendingRequests = pendingRequests;
  19. },
  20. };
  21. }
  22. exports.uniPostSourceMapPlugin = uniPostSourceMapPlugin;
  23. class PendingRequests extends Map {
  24. set(key, value) {
  25. const then = value.request.then;
  26. // @ts-expect-error
  27. value.request.then = (onFulfilled, onRejected) => {
  28. // @ts-expect-error
  29. return then.call(value.request, (request) => {
  30. const map = request?.map;
  31. if (map) {
  32. // @ts-expect-error
  33. const mod = this._server.moduleGraph._getUnresolvedUrlToModule(key);
  34. if (mod && mod.file && (0, path_1.isAbsolute)(mod.file)) {
  35. const dir = (0, uni_cli_shared_1.normalizePath)((0, path_1.dirname)(mod.file));
  36. if (dir.startsWith(this._inputDir)) {
  37. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  38. const sourcePath = map.sources[sourcesIndex];
  39. if (sourcePath) {
  40. // 将相对路径转换为绝对路径
  41. if (!(0, path_1.isAbsolute)(sourcePath)) {
  42. map.sources[sourcesIndex] = (0, uni_cli_shared_1.normalizePath)((0, path_1.join)(dir, sourcePath));
  43. }
  44. }
  45. }
  46. }
  47. }
  48. }
  49. return onFulfilled?.(request);
  50. }, onRejected);
  51. };
  52. return super.set(key, value);
  53. }
  54. }