-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.ts
84 lines (73 loc) · 2.22 KB
/
index.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
import { promises as fs } from 'fs'
import { resolve } from 'path'
import chokidar from 'chokidar'
type Options = Partial<{
storeDir: string
excludes: string[]
outputFile: string
isDev: boolean;
}>
const defaultOptions: Options = {
storeDir: 'src/store',
excludes: ['index'],
outputFile: 'src/helper/pinia-auto-refs.ts',
isDev: false,
}
export default function (options: Options = {}) {
options = { ...defaultOptions, ...options }
const { storeDir, excludes, outputFile,isDev } = options as Required<Options>
const storePath = resolve(process.cwd(), storeDir)
const outputDir = outputFile.replace(/(\/[^/]*).ts/, '')
fs.readdir(outputDir).catch(() => fs.mkdir(outputDir))
async function generateConfigFiles() {
const storesPath = await fs.readdir(storePath)
const storeNames = storesPath
.filter((i) => i.endsWith('.ts'))
.map((i) => i.replace('.ts', ''))
.filter((i) => !excludes.includes(i))
const ctx = `// "https://github.com/Allen-1998/pinia-auto-refs"
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
import type { AutoToRefs, ToRef } from 'vue'
${storeNames.reduce(
(str, storeName) => `${str}import ${storeName}Store from '${storeDir.replace(
'src',
'@'
)}/${storeName}'
`,
''
)}
import store from '${storeDir.replace(
'src',
'@'
)}'
declare module 'vue' {
export type AutoToRefs<T> = {
[K in keyof T]: T[K] extends Function ? T[K] : ToRef<T[K]>
}
}
const storeExports = {
${storeNames.reduce(
(str, storeName) => `${str} ${storeName}: ${storeName}Store,
`,
''
)}}
export function useStore<T extends keyof typeof storeExports>(storeName: T) {
const targetStore = storeExports[storeName](store)
const storeRefs = storeToRefs(targetStore)
return { ...targetStore, ...storeRefs } as unknown as AutoToRefs<ReturnType<typeof storeExports[T]>>
}
`
fs.writeFile(outputFile, ctx, 'utf-8')
}
generateConfigFiles()
if (process.env.NODE_ENV === 'development' || isDev) {
const watcher = chokidar.watch(storePath)
watcher.on('add', () => generateConfigFiles())
watcher.on('unlink', () => generateConfigFiles())
}
return {
name: 'pinia-auto-refs',
}
}