load.mjs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. // src/webpack/loaders/load.ts
  50. async function load(source, map) {
  51. const callback = this.async();
  52. const { unpluginName } = this.query;
  53. const plugin = this._compiler?.$unpluginContext[unpluginName];
  54. let id = this.resource;
  55. if (!plugin?.load || !id)
  56. return callback(null, source, map);
  57. const context = {
  58. error: (error) => this.emitError(typeof error === "string" ? new Error(error) : error),
  59. warn: (error) => this.emitWarning(typeof error === "string" ? new Error(error) : error)
  60. };
  61. if (id.startsWith(plugin.__virtualModulePrefix))
  62. id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length));
  63. const res = await plugin.load.call(
  64. Object.assign(this._compilation && createContext(this._compilation), context),
  65. normalizeAbsolutePath(id)
  66. );
  67. if (res == null)
  68. callback(null, source, map);
  69. else if (typeof res !== "string")
  70. callback(null, res.code, res.map ?? map);
  71. else
  72. callback(null, res, map);
  73. }
  74. export {
  75. load as default
  76. };