版博士V2.0程序
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 

63 行
2.0 KiB

  1. // src/core/index.ts
  2. import {
  3. DEFINE_PROPS,
  4. MagicString,
  5. WITH_DEFAULTS,
  6. getTransformResult,
  7. isCallOf,
  8. parseSFC
  9. } from "@vue-macros/common";
  10. function transformExportProps(code, id) {
  11. var _a;
  12. const { scriptSetup, getSetupAst } = parseSFC(code, id);
  13. if (!scriptSetup)
  14. return;
  15. const offset = scriptSetup.loc.start.offset;
  16. const s = new MagicString(code);
  17. const props = {};
  18. let hasDefineProps = false;
  19. function walkVariableDeclarator(decl) {
  20. if (decl.id.type !== "Identifier") {
  21. throw new Error("Only support identifier in export props");
  22. } else if (decl.init && (isCallOf(decl.init, DEFINE_PROPS) || isCallOf(decl.init, WITH_DEFAULTS))) {
  23. hasDefineProps = true;
  24. return;
  25. }
  26. const name = decl.id.name;
  27. const type = decl.id.typeAnnotation ? s.sliceNode(decl.id.typeAnnotation, { offset }) : ": any";
  28. const defaultValue = decl.init ? s.sliceNode(decl.init, { offset }) : void 0;
  29. props[name] = { type, defaultValue };
  30. }
  31. const setupAst = getSetupAst();
  32. for (const stmt of setupAst.body) {
  33. if (stmt.type === "ExportNamedDeclaration" && ((_a = stmt.declaration) == null ? void 0 : _a.type) === "VariableDeclaration") {
  34. for (const decl of stmt.declaration.declarations) {
  35. walkVariableDeclarator(decl);
  36. }
  37. s.removeNode(stmt, { offset });
  38. } else if (isCallOf(stmt, DEFINE_PROPS) || isCallOf(stmt, WITH_DEFAULTS)) {
  39. hasDefineProps = true;
  40. }
  41. }
  42. if (Object.keys(props).length === 0)
  43. return;
  44. else if (hasDefineProps)
  45. throw new Error("Don't support export props mixed with defineProps");
  46. let codegen = "";
  47. let destructureString = "";
  48. for (const [name, { type, defaultValue }] of Object.entries(props)) {
  49. codegen += ` ${name}${defaultValue ? "?" : ""}${type},
  50. `;
  51. destructureString += ` ${name}${defaultValue ? ` = ${defaultValue}` : ""},`;
  52. }
  53. codegen = `const {${destructureString} } = defineProps<{
  54. ${codegen}}>()`;
  55. s.prependLeft(offset, `
  56. ${codegen}`);
  57. return getTransformResult(s, id);
  58. }
  59. export {
  60. transformExportProps
  61. };