load.mjs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // src/webpack/context.ts
  2. import { resolve } from "path";
  3. import sources from "webpack-sources";
  4. import { Parser } from "acorn";
  5. function createContext(compilation) {
  6. return {
  7. parse(code, opts = {}) {
  8. return Parser.parse(code, {
  9. sourceType: "module",
  10. ecmaVersion: "latest",
  11. locations: true,
  12. ...opts
  13. });
  14. },
  15. addWatchFile(id) {
  16. (compilation.fileDependencies ?? compilation.compilationDependencies).add(
  17. resolve(process.cwd(), id)
  18. );
  19. },
  20. emitFile(emittedFile) {
  21. const outFileName = emittedFile.fileName || emittedFile.name;
  22. if (emittedFile.source && outFileName) {
  23. compilation.emitAsset(
  24. outFileName,
  25. sources ? new sources.RawSource(
  26. typeof emittedFile.source === "string" ? emittedFile.source : Buffer.from(emittedFile.source)
  27. ) : {
  28. source: () => emittedFile.source,
  29. size: () => emittedFile.source.length
  30. }
  31. );
  32. }
  33. },
  34. getWatchFiles() {
  35. return Array.from(
  36. compilation.fileDependencies ?? compilation.compilationDependencies
  37. );
  38. }
  39. };
  40. }
  41. // src/utils.ts
  42. import { isAbsolute, normalize } from "path";
  43. function normalizeAbsolutePath(path) {
  44. if (isAbsolute(path)) {
  45. return normalize(path);
  46. } else {
  47. return path;
  48. }
  49. }
  50. // src/webpack/loaders/load.ts
  51. async function load(source, map) {
  52. var _a;
  53. const callback = this.async();
  54. const { unpluginName } = this.query;
  55. const plugin = (_a = this._compiler) == null ? void 0 : _a.$unpluginContext[unpluginName];
  56. let id = this.resource;
  57. if (!(plugin == null ? void 0 : plugin.load) || !id) {
  58. return callback(null, source, map);
  59. }
  60. const context = {
  61. error: (error) => this.emitError(typeof error === "string" ? new Error(error) : error),
  62. warn: (error) => this.emitWarning(typeof error === "string" ? new Error(error) : error)
  63. };
  64. if (id.startsWith(plugin.__virtualModulePrefix)) {
  65. id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length));
  66. }
  67. const res = await plugin.load.call(
  68. Object.assign(this._compilation && createContext(this._compilation), context),
  69. normalizeAbsolutePath(id)
  70. );
  71. if (res == null) {
  72. callback(null, source, map);
  73. } else if (typeof res !== "string") {
  74. callback(null, res.code, res.map ?? map);
  75. } else {
  76. callback(null, res, map);
  77. }
  78. }
  79. export {
  80. load as default
  81. };