transform.mjs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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/webpack/loaders/transform.ts
  42. async function transform(source, map) {
  43. var _a;
  44. const callback = this.async();
  45. let unpluginName;
  46. if (typeof this.query === "string") {
  47. const query = new URLSearchParams(this.query);
  48. unpluginName = query.get("unpluginName");
  49. } else {
  50. unpluginName = this.query.unpluginName;
  51. }
  52. const plugin = (_a = this._compiler) == null ? void 0 : _a.$unpluginContext[unpluginName];
  53. if (!(plugin == null ? void 0 : plugin.transform)) {
  54. return callback(null, source, map);
  55. }
  56. const context = {
  57. error: (error) => this.emitError(typeof error === "string" ? new Error(error) : error),
  58. warn: (error) => this.emitWarning(typeof error === "string" ? new Error(error) : error)
  59. };
  60. const res = await plugin.transform.call(Object.assign(this._compilation && createContext(this._compilation), context), source, this.resource);
  61. if (res == null) {
  62. callback(null, source, map);
  63. } else if (typeof res !== "string") {
  64. callback(null, res.code, map == null ? map : res.map || map);
  65. } else {
  66. callback(null, res, map);
  67. }
  68. }
  69. export {
  70. transform as default
  71. };