-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscript.js
113 lines (95 loc) · 2.59 KB
/
script.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import _fs from 'fs'
import { rehype } from 'rehype'
import rehypeStringify from 'rehype-stringify'
import rehypeRewrite from 'rehype-rewrite'
import slugify from 'slugify'
const fs = _fs.promises
const FILE_PREFIX = 'icon-'
const EXTRA_PROPERTIES_TO_ADD = {
onclick: '{_handleClick}',
// add extra properties here
}
const SLUGIFY_CONFIG = {
replacement: '_',
strict: true,
}
main()
async function writeFile(fileName, fileContents, extension = 'html') {
fs.writeFile(
`${process.cwd()}${
extension === 'html' ? '/html' : ''
}/${fileName}.${extension}`,
fileContents
)
}
async function main() {
const sourceFolder = await fs.readdir(`${process.cwd()}\\svgs`)
console.log(`Reading ${sourceFolder.length} files from source folder.`)
const fileNames = []
await Promise.all(
sourceFolder.map(async (item) => {
const svgFile = await fs.readFile(`${process.cwd()}\\svgs\\${item}`)
const htmlFile = await rehype()
.data('settings', { fragment: true })
.use(rehypeRewrite, {
rewrite: (node) => {
if (node.tagName == 'svg') {
node.properties = {
...node.properties,
...EXTRA_PROPERTIES_TO_ADD,
}
}
},
})
.use(rehypeStringify)
.process(svgFile.toString())
// Drops the extra `"` around the functions above
const withFixes = Object.keys(EXTRA_PROPERTIES_TO_ADD).reduce(
(acc, item) => {
return acc.replace(
`"${EXTRA_PROPERTIES_TO_ADD[item]}"`,
EXTRA_PROPERTIES_TO_ADD[item]
)
},
String(htmlFile)
)
await writeFile(
`${FILE_PREFIX}${item.replace('.svg', '')}`,
`<template>${withFixes}</template>`
)
fileNames.push(item)
})
)
const javascriptFile = fileNames.reduce(
(acc, item) => {
const fileNameWithoutExtension = item.replace('.svg', '')
return {
imports: [
...acc.imports,
`import _${slugify(
fileNameWithoutExtension,
SLUGIFY_CONFIG
)} from './${FILE_PREFIX}${fileNameWithoutExtension}.html'`,
],
object: [
...acc.object,
`'${fileNameWithoutExtension}': _${slugify(
fileNameWithoutExtension,
SLUGIFY_CONFIG
)}`,
],
}
},
{
imports: [],
object: [],
}
)
const fileString = `
${javascriptFile.imports.join('\n')}
export const ICONS = {
${javascriptFile.object.join(',\n')}
}
`
await writeFile(`icons`, fileString, 'js')
}