Last active 1741880026

Revision e6db1af1a35c5417642187db594c09020145b53d

convert-vue2-vue3-comp.js Raw
1// Put everything under export default { into exported (as an object)
2const exported = {}
3
4function cleanCode(input) {
5 return input
6 .replace(/this\.([a-zA-Z$_]+)\(/g, '$1(')
7 .replace(/this\.([a-zA-Z$_]+)/g, '$1.value')
8 .replace(/\$emit/g, 'emit')
9 .replace(/\$(route|router)\.value/g, '$1')
10}
11
12function getData() {
13 let data = exported.data()
14 let output = ""
15 for(var key in data) {
16 let v = data[key]
17 if(v && typeof v === "object") {
18 v = JSON.stringify(data[key], null, 2).replace(/"([^"]+)":/g, '$1:')
19 }
20 output += `let ${key} = ref(${v})\n`
21 }
22 return output
23}
24
25function getWatch() {
26 let output = ""
27 if(exported.watch) {
28 for(const key in exported.watch) {
29 let func = exported.watch[key].handler.toString()
30 .replace(/handler\((.*)\)\s*{(.*)}/s, (match, p1, p2) => {
31 return `(${p1}) => { ${cleanCode(p2)} }`
32 })
33 output += `watch(${key}, ${func})\n`
34 }
35 }
36 return output
37}
38
39function getComputed() {
40 let output = ""
41 if(exported.computed) {
42 for(const key in exported.computed) {
43 let func = exported.computed[key].toString()
44 .replace(new RegExp(`${key}\\s*\\((.*)\\)\\s*{(.*)}`,'s'), (match, p1, p2) => {
45 return `(${p1}) => { ${cleanCode(p2)} }`
46 })
47 output += `const ${key} = computed(${func})\n`
48 }
49 }
50 return output
51}
52
53function getMethods() {
54 let output = ""
55 if(exported.methods) {
56 for(const key in exported.methods) {
57 let func = exported.methods[key].toString()
58 .replace(/([a-zA-Z\s]+\s)?([a-zA-Z_]+)\s*\(([a-zA-Z,\s]*)\)\s*{(.*)}/s, (match, p1, p2, p3, p4) => {
59 return `${p1||''}function ${p2}(${p3}) {\n${cleanCode(p4)}\n}\n`
60 })
61 output += func
62 }
63 }
64 return output
65}
66
67function getHooks() {
68 let output = ""
69 if(exported.created) {
70 const rawfunc = exported.created.toString()
71 const func = rawfunc.slice(rawfunc.indexOf("{") + 1, rawfunc.lastIndexOf("}"));
72 output += `onBeforeMount(() => {\n${cleanCode(func)}\n})`
73 }
74 if(exported.mounted) {
75 const rawfunc = exported.mounted.toString()
76 const func = rawfunc.slice(rawfunc.indexOf("{") + 1, rawfunc.lastIndexOf("}"));
77 output += `onMounted(() => {\n${cleanCode(func)}\n})`
78 }
79 return output
80}
81
82
83let output = `import { ref, watch, computed, onBeforeMount, onMounted } from 'vue'\n`
84output += `import { useRoute, useRouter } from 'vue-router'\n`
85output += `const route = useRoute()\nconst router = useRouter()\n`
86output += getData() + "\n"
87output += getWatch() + "\n"
88output += getComputed() + "\n"
89output += getMethods() + "\n"
90output += getHooks() + "\n"
91
92console.log(output)