load.mjs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // src/rspack/context.ts
  2. import { Buffer } from "buffer";
  3. import sources from "webpack-sources";
  4. import { Parser } from "acorn";
  5. function createBuildContext(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() {
  16. },
  17. emitFile(emittedFile) {
  18. const outFileName = emittedFile.fileName || emittedFile.name;
  19. if (emittedFile.source && outFileName) {
  20. compilation.emitAsset(
  21. outFileName,
  22. new sources.RawSource(
  23. // @ts-expect-error types mismatch
  24. typeof emittedFile.source === "string" ? emittedFile.source : Buffer.from(emittedFile.source)
  25. )
  26. );
  27. }
  28. },
  29. getWatchFiles() {
  30. return [];
  31. }
  32. };
  33. }
  34. function createContext(loader) {
  35. return {
  36. error: (error) => loader.emitError(normalizeMessage(error)),
  37. warn: (message) => loader.emitWarning(normalizeMessage(message))
  38. };
  39. }
  40. function normalizeMessage(error) {
  41. const err = new Error(typeof error === "string" ? error : error.message);
  42. if (typeof error === "object") {
  43. err.stack = error.stack;
  44. err.cause = error.meta;
  45. }
  46. return err;
  47. }
  48. // src/utils.ts
  49. import { isAbsolute, normalize } from "path";
  50. function normalizeAbsolutePath(path) {
  51. if (isAbsolute(path))
  52. return normalize(path);
  53. else
  54. return path;
  55. }
  56. // src/rspack/loaders/load.ts
  57. async function load(source, map) {
  58. const callback = this.async();
  59. const { unpluginName } = this.query;
  60. const plugin = this._compiler?.$unpluginContext[unpluginName];
  61. const id = this.resource;
  62. if (!plugin?.load || !id)
  63. return callback(null, source, map);
  64. if (plugin.loadInclude && !plugin.loadInclude(id))
  65. return callback(null, source, map);
  66. const context = createContext(this);
  67. const res = await plugin.load.call(
  68. Object.assign(
  69. this._compilation && createBuildContext(this._compilation),
  70. context
  71. ),
  72. normalizeAbsolutePath(id)
  73. );
  74. if (res == null)
  75. callback(null, source, map);
  76. else if (typeof res !== "string")
  77. callback(null, res.code, res.map ?? map);
  78. else
  79. callback(null, res, map);
  80. }
  81. export {
  82. load as default
  83. };