-
Notifications
You must be signed in to change notification settings - Fork 0
/
findSvgPlugin.ts
79 lines (76 loc) · 2.26 KB
/
findSvgPlugin.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 fs from 'fs'
import path from 'path'
import process from 'process'
import { type Plugin, createLogger } from 'vite'
import { getAssetsDir } from './utils'
const findSvgPlugin = () => {
const map = new Map()
const outFile = () => {
const targetDir = getAssetsDir()
if (fs.existsSync(targetDir)) {
fs.rmdirSync(targetDir, { recursive: true })
}
fs.mkdirSync(targetDir, {
recursive: true,
})
const data: { [key: string]: string[] } = Array.from(map.entries()).reduce(
(acc: { [key: string]: string[] }, [key, value]) => {
acc[key] = Array.from(value)
return acc
},
{},
)
let count = 0
const newData: Record<string, string[]> = {}
Object.entries(data).forEach(([key, value]) => {
const name = path.relative(process.cwd(), key).replace(/\//g, '_')
const sourcePath = path.join(key)
const targetPath = path.join(targetDir, name)
newData[name] = value.map((item) => {
return path.relative(process.cwd(), item).split('?')[0]
})
fs.copyFile(sourcePath, targetPath, (error) => {
if (error) {
console.log(error)
} else {
console.log('copied ' + targetPath)
count++
}
})
// archive.append(content, { name: name });
})
fs.writeFileSync(
path.join(targetDir, 'svg-importer.json'),
JSON.stringify(newData),
)
console.log(`copied ${count} svg files`)
}
const logger = createLogger()
return {
name: 'find-svg-plugin',
enforce: 'pre',
apply: 'build',
resolveId(id, importer) {
if (id.endsWith('.svg') && !importer?.endsWith('index.html')) {
let relativeKeyPath
if (path.isAbsolute(id)) {
relativeKeyPath = path.resolve(id)
} else {
relativeKeyPath = path.resolve(path.dirname(importer!), id)
}
relativeKeyPath = path.resolve(relativeKeyPath)
const relativeValuePath = path.resolve(importer!)
if (map.has(relativeKeyPath)) {
map.get(relativeKeyPath).add(relativeValuePath)
} else {
map.set(relativeKeyPath, new Set([relativeValuePath]))
}
}
return null
},
closeBundle() {
outFile()
},
} as Plugin
}
export default findSvgPlugin