-
Notifications
You must be signed in to change notification settings - Fork 4
/
vite-plugin-index-builder.js
81 lines (68 loc) · 2.54 KB
/
vite-plugin-index-builder.js
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
import fs from 'fs/promises'
import path from 'path'
const fontsPathName = 'fonts'
const rootDir = process.cwd()
async function listDirectories(dir) {
const dirents = await fs.readdir(dir, {withFileTypes: true})
return dirents
.filter(dirent => dirent.isDirectory() && dirent.name !== fontsPathName)
.map(dirent => dirent.name)
}
async function listFiles(dir) {
const dirents = await fs.readdir(dir, {withFileTypes: true})
return dirents
.filter(dirent => dirent.isFile() && dirent.name.endsWith('.png'))
.map(dirent => dirent.name)
}
async function readJsonFile(filePath) {
try {
const content = await fs.readFile(filePath, 'utf8')
return JSON.parse(content)
} catch (err) {
return {}
}
}
export default function buildDataIndex(dataPath) {
return {
name: 'build-data-index',
apply: 'build',
async generateBundle(_, bundle) {
const dataSubDirs = await listDirectories(path.join(rootDir, dataPath))
const dataTemplateNames = dataSubDirs
let fontsNames = []
const fontsDirPath = path.join(rootDir, dataPath, fontsPathName)
try {
await fs.access(fontsDirPath)
fontsNames = await listFiles(fontsDirPath)
} catch (e) {
}
const jsonData = {
version: 0.1,
dataPath,
dataList: dataTemplateNames,
fontList: fontsNames
}
await fs.writeFile(path.join(rootDir, 'index.json'), JSON.stringify(jsonData, null, 4))
const lengthIndex = {}
const aliasIndex = {}
const typeIndex = {}
for (const dir of dataSubDirs) {
if (dir !== fontsPathName) {
const dirPath = path.join(rootDir, dataPath, dir)
const files = await listFiles(dirPath)
lengthIndex[dir] = files.length
const dataJsonFile = path.join(rootDir, dataPath, dir, 'data.json')
const dataJson = await readJsonFile(dataJsonFile)
aliasIndex[dir] = dataJson.alias || []
typeIndex[dir] = dataJson.type || 'Unknown'
}
}
const indexMapJsonData = JSON.stringify({
length: lengthIndex,
alias: aliasIndex,
type: typeIndex
})
await fs.writeFile(path.join(rootDir, 'index.map.json'), indexMapJsonData)
}
}
}