-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.js
154 lines (139 loc) · 4.4 KB
/
build.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import fs from 'fs';
import path from 'path';
import recursiveReaddir from 'recursive-readdir';
import { optimize } from 'svgo';
function toPascalCase(string) {
return `${string}`
.toLowerCase()
.replace(new RegExp(/[-_]+/, 'g'), ' ')
.replace(new RegExp(/[^\w\s]/, 'g'), ' ')
.replace(
new RegExp(/\s+(.)(\w*)/, 'g'),
($1, $2, $3) => `${$2.toUpperCase() + $3}`
)
.replace(new RegExp(/\w/), s => s.toUpperCase());
}
function clearDirectory(dirPath) {
if (fs.existsSync(dirPath)) {
fs.rmSync(dirPath, { recursive: true, force: true });
}
}
function readAndOptimizeSVG(file) {
const fileName = path.basename(file, '.svg');
const svgContent = fs.readFileSync(file, 'utf-8');
return optimize(svgContent, {
multipass: true,
plugins: [
{
name: 'preset-default',
params: {
overrides: {
removeViewBox: false,
removeUnknownsAndDefaults: false,
convertShapeToPath: false,
collapseGroups: false,
removeUselessDefs: false,
},
},
},
{
name: 'removeComments',
},
{ name: 'cleanupIds',
params: {
overrides: {
remove: false,
minify: false,
},
},
},
{
name: 'prefixIds',
params: {
delim: '-gui-asset-',
prefix: fileName,
prefixIds: true,
prefixClassNames: true
},
},
],
});
}
function ensureDirectoryExists(dirPath) {
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
}
function createVueComponent(file, optimizedSvg, outputSubDir) {
const fileName = path.basename(file, '.svg');
const variant = path.basename(outputSubDir)
const fileNameWithPostfix = `${variant}-${fileName}`
const pascalCaseFileName = toPascalCase(fileNameWithPostfix);
const modifiedSvg = optimizedSvg.replace(
/<svg([^>]*?)>/,
`<svg$1 :style="computedStyles">`
);
const vueFileContent = `
<script lang="ts" setup>
import { computed } from 'vue';
interface ${pascalCaseFileName}Props {
width?: string;
height?: string;
}
const props = defineProps<${pascalCaseFileName}Props>();
const computedStyles = computed(() => ({
width: props.width || '1em',
height: props.height || '1em',
minWidth: props.width || '1em',
minHeight: props.height || '1em',
}));
</script>
<template>
${modifiedSvg}
</template>
`;
const vueFilePath = path.join(outputSubDir, `${pascalCaseFileName}.vue`);
fs.writeFileSync(vueFilePath, vueFileContent);
console.log(`Component for ${fileName}.svg created at ${vueFilePath}`);
return { vueFilePath, pascalCaseFileName };
}
function updateIndexFile(outputSubDir, pascalCaseFileName) {
const indexFilePath = path.join(outputSubDir, 'index.ts');
const exportStatement = `export { default as ${pascalCaseFileName} } from './${pascalCaseFileName}.vue';\n`;
if (fs.existsSync(indexFilePath)) {
fs.appendFileSync(indexFilePath, exportStatement);
} else {
fs.writeFileSync(indexFilePath, exportStatement);
}
}
function generateBuildIndex(outputDir) {
const allDirs = fs.readdirSync(outputDir, { withFileTypes: true }).filter(item => item.isDirectory()).map(dir => dir.name);
const buildIndexPath = path.join(outputDir, 'index.ts');
let buildIndexContent = '';
allDirs.forEach(dir => {
buildIndexContent += `export * from './${dir}';\n`;
});
fs.writeFileSync(buildIndexPath, buildIndexContent);
console.log('Generated build/index.ts with re-exports for all components.');
}
async function generateVueComponents(inputDir, outputDir) {
try {
clearDirectory(outputDir);
ensureDirectoryExists(outputDir);
const svgFiles = await recursiveReaddir(inputDir, ['!*.svg']);
for (const file of svgFiles) {
const { data: optimizedSvg } = readAndOptimizeSVG(file);
const relativePath = path.relative(inputDir, path.dirname(file));
const outputSubDir = path.join(outputDir, relativePath);
ensureDirectoryExists(outputSubDir);
const { pascalCaseFileName } = createVueComponent(file, optimizedSvg, outputSubDir);
updateIndexFile(outputSubDir, pascalCaseFileName);
}
generateBuildIndex(outputDir);
} catch (error) {
console.error('Error while generating Vue components:', error);
}
}
const inputDirectory = './assets';
const outputDirectory = './build';
generateVueComponents(inputDirectory, outputDirectory);