版博士V2.0程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

load.mjs 2.3 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. // @ts-expect-error types mismatch
  27. typeof emittedFile.source === "string" ? emittedFile.source : Buffer.from(emittedFile.source)
  28. ) : {
  29. source: () => emittedFile.source,
  30. size: () => emittedFile.source.length
  31. }
  32. );
  33. }
  34. },
  35. getWatchFiles() {
  36. return Array.from(
  37. compilation.fileDependencies ?? compilation.compilationDependencies
  38. );
  39. }
  40. };
  41. }
  42. // src/utils.ts
  43. import { isAbsolute, normalize } from "path";
  44. function normalizeAbsolutePath(path) {
  45. if (isAbsolute(path))
  46. return normalize(path);
  47. else
  48. return path;
  49. }
  50. // src/webpack/loaders/load.ts
  51. async function load(source, map) {
  52. const callback = this.async();
  53. const { unpluginName } = this.query;
  54. const plugin = this._compiler?.$unpluginContext[unpluginName];
  55. let id = this.resource;
  56. if (!plugin?.load || !id)
  57. return callback(null, source, map);
  58. const context = {
  59. error: (error) => this.emitError(typeof error === "string" ? new Error(error) : error),
  60. warn: (error) => this.emitWarning(typeof error === "string" ? new Error(error) : error)
  61. };
  62. if (id.startsWith(plugin.__virtualModulePrefix))
  63. id = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length));
  64. const res = await plugin.load.call(
  65. Object.assign(this._compilation && createContext(this._compilation), context),
  66. normalizeAbsolutePath(id)
  67. );
  68. if (res == null)
  69. callback(null, source, map);
  70. else if (typeof res !== "string")
  71. callback(null, res.code, res.map ?? map);
  72. else
  73. callback(null, res, map);
  74. }
  75. export {
  76. load as default
  77. };