runtimeHooks.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.uniRuntimeHooksPlugin = void 0;
  4. const uni_shared_1 = require("@dcloudio/uni-shared");
  5. const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
  6. const compiler_sfc_1 = require("@vue/compiler-sfc");
  7. function uniRuntimeHooksPlugin() {
  8. return {
  9. name: 'uni:mp-runtime-hooks',
  10. enforce: 'post',
  11. async transform(source, id) {
  12. const isSetupJs = (0, uni_cli_shared_1.isUniPageSfcFile)(id);
  13. const isSetupTs = !isSetupJs && (0, uni_cli_shared_1.isUniPageSetupAndTs)(id);
  14. if (!isSetupJs && !isSetupTs) {
  15. return null;
  16. }
  17. if (isSetupJs && !source.includes('_sfc_main')) {
  18. return null;
  19. }
  20. if (isSetupTs && !source.includes('defineComponent')) {
  21. return null;
  22. }
  23. const matches = source.match(new RegExp(`(${Object.keys(uni_shared_1.MINI_PROGRAM_PAGE_RUNTIME_HOOKS).join('|')})`, 'g'));
  24. if (!matches) {
  25. return null;
  26. }
  27. if (matches.includes('onShareTimeline')) {
  28. matches.push('onShareAppMessage');
  29. }
  30. const hooks = new Set(matches);
  31. let flag = 0;
  32. for (const hook of hooks) {
  33. flag |= uni_shared_1.MINI_PROGRAM_PAGE_RUNTIME_HOOKS[hook];
  34. }
  35. if (isSetupJs) {
  36. source = source + `;_sfc_main.__runtimeHooks = ${flag};`;
  37. }
  38. else if (isSetupTs) {
  39. source =
  40. (0, compiler_sfc_1.rewriteDefault)(source, '_sfc_defineComponent') +
  41. `\n_sfc_defineComponent.__runtimeHooks = ${flag};\nexport default _sfc_defineComponent`;
  42. }
  43. return {
  44. code: source,
  45. map: { mappings: '' },
  46. };
  47. },
  48. };
  49. }
  50. exports.uniRuntimeHooksPlugin = uniRuntimeHooksPlugin;