This repository has been archived by the owner on Nov 1, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
computed.ts
79 lines (64 loc) · 2.35 KB
/
computed.ts
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
import { types } from '@babel/core'
import { getSetupMethod } from '../../ast-utilities'
export function addComputed(ast: types.File, section: types.ObjectProperty) {
const setupMethodBody = getSetupMethod(ast).body.body
const computedProps = section.value as types.ObjectExpression
const properties = computedProps.properties
const toExportList = []
for (let i = 0; i < properties.length; i += 1) {
const property = properties[i]
if (types.isObjectMethod(property)) {
const key = property.key as types.Identifier
const computedStatement = types.variableDeclaration('const', [
types.variableDeclarator(
types.identifier(key.name),
types.callExpression(types.identifier('computed'), [
types.arrowFunctionExpression([], property.body)
])
)
])
toExportList.push(key.name)
setupMethodBody.splice(1, 0, computedStatement)
continue
}
if (types.isObjectProperty(property)) {
const key = property.key as types.Identifier
const value = property.value
if (types.isArrowFunctionExpression(value)) {
const computedStatement = types.variableDeclaration('const', [
types.variableDeclarator(
types.identifier(key.name),
types.callExpression(types.identifier('computed'), [value])
)
])
toExportList.push(key.name)
setupMethodBody.splice(1, 0, computedStatement)
}
if (types.isFunctionExpression(value)) {
const computedStatement = types.variableDeclaration('const', [
types.variableDeclarator(
types.identifier(key.name),
types.callExpression(types.identifier('computed'), [
types.arrowFunctionExpression([], value.body)
])
)
])
toExportList.push(key.name)
setupMethodBody.splice(1, 0, computedStatement)
}
}
// if (types.isSpreadElement(property)) {}
}
// export computed properties
const returnStatement = setupMethodBody.slice(-1)[0] as types.ReturnStatement
const argument = returnStatement.argument as types.ObjectExpression
toExportList.forEach(exportItem => {
argument.properties.push(
types.objectProperty(
types.identifier(exportItem),
types.identifier(exportItem)
)
)
})
// TODO: update computed prop usage
}