1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| const { parse } = require("@babel/parser"); const { parse: vueParse } = require("@vue/compiler-sfc"); const fs = require("fs");
const isFunctionExpression = (type) => { return type === "FunctionExpression" || type === "ArrowFunctionExpression"; };
const parseAST = (node, handleFunction) => { if (node.type === "File") { node.program.body.forEach((n) => parseAST(n, handleFunction)); } else if (node.type === "ExportDefaultDeclaration") { parseAST(node.declaration, handleFunction); } else if (node.type === "CallExpression") { node.arguments.forEach((arg) => parseAST(arg, handleFunction)); } else if (node.type === "ObjectMethod") { if (node.key.name === "setup") { node.body.body.forEach((n) => parseAST(n, handleFunction)); } else { handleFunction(node.key.name, node.leadingComments); } } else if (node.type === "ObjectExpression") { node.properties.forEach((property) => parseAST(property, handleFunction)); } else if (node.type === "FunctionDeclaration") { handleFunction(node.id.name, node.leadingComments); } else if (node.type === "VariableDeclaration") { const declaration = node.declarations[0]; if (declaration.init && isFunctionExpression(declaration.init.type)) { handleFunction(declaration.id.name, node.leadingComments); } else { parseAST(declaration.init, handleFunction); } } else if (node.type === "ObjectProperty") { if (isFunctionExpression(node.value.type)) { handleFunction(node.key.name, node.leadingComments); } else if (node.value.type === "ObjectExpression") { node.value.properties.forEach((property) => parseAST(property, handleFunction) ); } } };
const getFileContent = (filePath) => { return fs.readFileSync(filePath, "utf8"); };
const getScriptContent = (descriptor) => { return descriptor.script ? descriptor.script.content : descriptor.scriptSetup ? descriptor.scriptSetup.content : descriptor.source ? descriptor.source : ""; };
module.exports.parseVueComments = (filePath, handleFunction) => { const fileContent = getFileContent(filePath); const { descriptor } = vueParse(fileContent); const scriptContent = parse(getScriptContent(descriptor), { sourceType: "module", plugins: ["jsx"], }); parseAST(scriptContent, handleFunction); };
|