wxs.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.genWxsCallMethodsCode = exports.parseWxsCallMethods = void 0;
  4. const types_1 = require("@babel/types");
  5. const estree_walker_1 = require("estree-walker");
  6. const ast_1 = require("./ast");
  7. function parseWxsCallMethods(code) {
  8. if (!code.includes('callMethod')) {
  9. return [];
  10. }
  11. const ast = (0, ast_1.parseProgram)(code, '', {});
  12. const wxsCallMethods = new Set();
  13. estree_walker_1.walk(ast, {
  14. enter(child) {
  15. if (!(0, types_1.isCallExpression)(child)) {
  16. return;
  17. }
  18. const { callee } = child;
  19. // .callMethod
  20. if (!(0, types_1.isMemberExpression)(callee) ||
  21. !(0, types_1.isIdentifier)(callee.property) ||
  22. callee.property.name !== 'callMethod') {
  23. return;
  24. }
  25. // .callMethod('test',...)
  26. const args = child.arguments;
  27. if (!args.length) {
  28. return;
  29. }
  30. const [name] = args;
  31. if (!(0, types_1.isStringLiteral)(name)) {
  32. return;
  33. }
  34. wxsCallMethods.add(name.value);
  35. },
  36. });
  37. return [...wxsCallMethods];
  38. }
  39. exports.parseWxsCallMethods = parseWxsCallMethods;
  40. function genWxsCallMethodsCode(code) {
  41. const wxsCallMethods = parseWxsCallMethods(code);
  42. if (!wxsCallMethods.length) {
  43. return `export default {}`;
  44. }
  45. return `export default (Component) => {
  46. if(!Component.wxsCallMethods){
  47. Component.wxsCallMethods = []
  48. }
  49. Component.wxsCallMethods.push(${wxsCallMethods
  50. .map((m) => `'${m}'`)
  51. .join(', ')})
  52. }
  53. `;
  54. }
  55. exports.genWxsCallMethodsCode = genWxsCallMethodsCode;