-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathvue-router-v4.ts
99 lines (86 loc) · 2.96 KB
/
vue-router-v4.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import wrap from '../src/wrapAstTransformation'
import type { ASTTransformation } from '../src/wrapAstTransformation'
import { transformAST as addImport } from './add-import'
import { transformAST as removeExtraneousImport } from './remove-extraneous-import'
import type { ObjectExpression } from 'jscodeshift'
// new Router() -> createRouter()
export const transformAST: ASTTransformation = (context) => {
const { root, j } = context
const routerImportDecls = root.find(j.ImportDeclaration, {
source: {
value: 'vue-router',
},
})
const importedVueRouter = routerImportDecls.find(j.ImportDefaultSpecifier)
if (importedVueRouter.length) {
const localVueRouter = importedVueRouter.get(0).node.local.name
const newVueRouter = root.find(j.NewExpression, {
callee: {
type: 'Identifier',
name: localVueRouter,
},
})
addImport(context, {
specifier: { type: 'named', imported: 'createRouter' },
source: 'vue-router',
})
newVueRouter.replaceWith(({ node }) => {
// mode: 'history' -> history: createWebHistory(), etc
let historyMode = 'createWebHashHistory'
let baseValue
if (!j.ObjectExpression.check(node.arguments[0])) {
throw new Error(
'Currently, only object expressions passed to `new VueRouter` can be transformed.'
)
}
const routerConfig: ObjectExpression = node.arguments[0]
routerConfig.properties = routerConfig.properties.filter((p) => {
if (!j.ObjectProperty.check(p) && !j.Property.check(p)) {
return true
}
if ((p.key as any).name === 'mode') {
const mode = (p.value as any).value
if (mode === 'hash') {
historyMode = 'createWebHashHistory'
} else if (mode === 'history') {
historyMode = 'createWebHistory'
} else if (mode === 'abstract') {
historyMode = 'createMemoryHistory'
} else {
throw new Error(
`mode must be one of 'hash', 'history', or 'abstract'`
)
}
return false
} else if ((p.key as any).name === 'base') {
baseValue = p.value
return false
}
return true
})
// add the default mode with a hash history
addImport(context, {
specifier: { type: 'named', imported: historyMode },
source: 'vue-router',
})
node.arguments[0].properties = node.arguments[0].properties.filter(
(p) => !!p
)
node.arguments[0].properties.unshift(
j.objectProperty(
j.identifier('history'),
j.callExpression(
j.identifier(historyMode),
baseValue ? [baseValue] : []
)
)
)
return j.callExpression(j.identifier('createRouter'), node.arguments)
})
removeExtraneousImport(context, {
localBinding: localVueRouter,
})
}
}
export default wrap(transformAST)
export const parser = 'babylon'