-
-
Notifications
You must be signed in to change notification settings - Fork 369
/
Copy pathdeclaration.ts
65 lines (55 loc) · 1.78 KB
/
declaration.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
import { resolve, dirname, relative } from 'path'
import { promises as fs, existsSync } from 'fs'
import { notNullish, slash } from '@antfu/utils'
import { Context } from './context'
export function parseDeclaration(code: string): Record<string, string> {
return Object.fromEntries(Array.from(code.matchAll(/(?<!\/\/)\s+\s+['"]?(.+?)['"]?:\s(.+?)\n/g)).map(i => [i[1], i[2]]))
}
export async function generateDeclaration(ctx: Context, root: string, filepath: string) {
const imports: Record<string, string> = Object.fromEntries(
Object.values({
...ctx.componentNameMap,
...ctx.componentCustomMap,
})
.map(({ path, name, importName }) => {
if (!name)
return undefined
const related = slash(path).startsWith('/')
? `./${relative(dirname(filepath), path)}`
: path
let entry = `typeof import('${slash(related)}')`
if (importName)
entry += `['${importName}']`
else
entry += '[\'default\']'
return [name, entry]
})
.filter(notNullish),
)
if (!Object.keys(imports).length)
return
const originalImports = existsSync(filepath)
? parseDeclaration(await fs.readFile(filepath, 'utf-8'))
: {}
const lines = Object.entries({
...originalImports,
...imports,
})
.sort((a, b) => a[0].localeCompare(b[0]))
.map(([name, v]) => {
if (!/^\w+$/.test(name))
name = `'${name}'`
return `${name}: ${v}`
})
const code = `// generated by unplugin-vue-components
// We suggest you to commit this file into source control
// Read more: https://github.com/vuejs/vue-next/pull/3399
declare module 'vue' {
export interface GlobalComponents {
${lines.join('\n ')}
}
}
export { }
`
await fs.writeFile(filepath, code, 'utf-8')
}