vite-plugin-svg-spritegen 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +56 -0
- package/dist/build-svg-map.d.ts +2 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +241 -0
- package/dist/index.mjs +241 -0
- package/dist/types.d.ts +29 -0
- package/dist/write-gitignore.d.ts +1 -0
- package/dist/write-if-changed.d.ts +1 -0
- package/dist/write-sprite.d.ts +2 -0
- package/dist/write-types.d.ts +2 -0
- package/package.json +72 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Forge 42
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+

|
|
2
|
+

|
|
3
|
+

|
|
4
|
+
|
|
5
|
+
# vite-plugin-svg-spritegen
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
## Installation
|
|
9
|
+
```bash
|
|
10
|
+
npm install -D vite-plugin-svg-spritegen
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
```typescript
|
|
15
|
+
// vite.config.js
|
|
16
|
+
import { svgSpritegen } from 'vite-plugin-svg-spritegen';
|
|
17
|
+
|
|
18
|
+
export default {
|
|
19
|
+
plugins: [
|
|
20
|
+
svgSpritegen({
|
|
21
|
+
input: [
|
|
22
|
+
{
|
|
23
|
+
baseDir: 'src/assets/icons',
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
baseDir: 'node_modules/lucide-static/icons',
|
|
27
|
+
removeAttrs: ['class', 'stroke-width', 'stroke-linecap', 'stroke-linejoin']
|
|
28
|
+
}
|
|
29
|
+
],
|
|
30
|
+
outputDir: 'src/assets/icons'
|
|
31
|
+
})
|
|
32
|
+
],
|
|
33
|
+
};
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### Example Icon Component
|
|
37
|
+
|
|
38
|
+
```jsx
|
|
39
|
+
import spriteHref from '~/assets/icons/sprite.svg';
|
|
40
|
+
import type { FC, SVGProps } from 'react';
|
|
41
|
+
import type { IconName } from '~/assets/icons/types';
|
|
42
|
+
|
|
43
|
+
export const IconBase: FC<SVGProps<SVGSVGElement> & { name: IconName }> = ({ name, ...props }) => {
|
|
44
|
+
return (
|
|
45
|
+
<svg {...props}>
|
|
46
|
+
<use href={`${spriteHref}#${name}`} />
|
|
47
|
+
</svg>
|
|
48
|
+
);
|
|
49
|
+
};
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### Usage Example
|
|
53
|
+
|
|
54
|
+
```jsx
|
|
55
|
+
<Icon name="plus" />
|
|
56
|
+
```
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const path = require("node:path");
|
|
4
|
+
const chokidar = require("chokidar");
|
|
5
|
+
const vite = require("vite");
|
|
6
|
+
const fastGlob = require("fast-glob");
|
|
7
|
+
const node_fs = require("node:fs");
|
|
8
|
+
const nodeHtmlParser = require("node-html-parser");
|
|
9
|
+
const svgo = require("svgo");
|
|
10
|
+
const buildSvgMap = async (inputConfigs) => {
|
|
11
|
+
const svgMap = /* @__PURE__ */ new Map();
|
|
12
|
+
for (const inputConfig of inputConfigs) {
|
|
13
|
+
const { pattern, baseDir, getSymbolId } = inputConfig;
|
|
14
|
+
const matchPaths = await fastGlob(pattern, { cwd: baseDir });
|
|
15
|
+
for (const matchPath of matchPaths) {
|
|
16
|
+
const resolvedInputConfig = {
|
|
17
|
+
...inputConfig,
|
|
18
|
+
matchPath,
|
|
19
|
+
filePath: path.join(baseDir, matchPath)
|
|
20
|
+
};
|
|
21
|
+
const symbolId = getSymbolId(resolvedInputConfig);
|
|
22
|
+
if (svgMap.has(symbolId)) {
|
|
23
|
+
console.log(
|
|
24
|
+
`Duplicate SVG symbol id "${symbolId}. Symbol ids should be unique across all inputs."`
|
|
25
|
+
);
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
svgMap.set(symbolId, { ...resolvedInputConfig, symbolId });
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return svgMap;
|
|
32
|
+
};
|
|
33
|
+
const writeIfChanged = async (filePath, content) => {
|
|
34
|
+
try {
|
|
35
|
+
const currentContent = await node_fs.promises.readFile(filePath, "utf8");
|
|
36
|
+
if (content && currentContent !== content) {
|
|
37
|
+
await node_fs.promises.writeFile(filePath, content, "utf8");
|
|
38
|
+
}
|
|
39
|
+
} catch (e) {
|
|
40
|
+
await node_fs.promises.writeFile(filePath, content ?? "", "utf8");
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
const writeTypes = async (filePath, svgMap) => {
|
|
44
|
+
const iconNames = [...svgMap.keys()];
|
|
45
|
+
const content = [
|
|
46
|
+
"/* eslint-disable */",
|
|
47
|
+
"",
|
|
48
|
+
"// This file is autogenerated. Do not commit to source control.",
|
|
49
|
+
"",
|
|
50
|
+
"export type IconName = (typeof iconNames)[number];",
|
|
51
|
+
"",
|
|
52
|
+
"export const iconNames = [",
|
|
53
|
+
...iconNames.map((name) => ` '${name}',`),
|
|
54
|
+
"] as const;",
|
|
55
|
+
""
|
|
56
|
+
].join("\n");
|
|
57
|
+
await writeIfChanged(filePath, content);
|
|
58
|
+
};
|
|
59
|
+
const writeGitignore = async (filePath, spriteName, typesName) => {
|
|
60
|
+
const content = ["# svg spritegen", spriteName, typesName].join("\n");
|
|
61
|
+
try {
|
|
62
|
+
const currentContent = await node_fs.promises.readFile(filePath, "utf8");
|
|
63
|
+
if (currentContent.includes(content)) {
|
|
64
|
+
return;
|
|
65
|
+
} else {
|
|
66
|
+
await node_fs.promises.writeFile(filePath, currentContent + "\n" + content, "utf8");
|
|
67
|
+
}
|
|
68
|
+
} catch (e) {
|
|
69
|
+
await node_fs.promises.writeFile(filePath, content, "utf8");
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
const writeSprite = async (spritePath, svgMap) => {
|
|
73
|
+
const symbols = [];
|
|
74
|
+
const definitions = [];
|
|
75
|
+
await Promise.all(
|
|
76
|
+
[...svgMap.values()].map(async (inputConfig) => {
|
|
77
|
+
const { svgo: svgo$1, removeAttrs, symbolId, filePath } = inputConfig;
|
|
78
|
+
if (spritePath === filePath) return;
|
|
79
|
+
let svgContent = await node_fs.promises.readFile(filePath, "utf8");
|
|
80
|
+
if (svgo$1 !== false) {
|
|
81
|
+
svgContent = svgo.optimize(svgContent, {
|
|
82
|
+
...svgo$1,
|
|
83
|
+
plugins: [
|
|
84
|
+
...svgo$1.plugins ?? [],
|
|
85
|
+
...removeAttrs.length ? [
|
|
86
|
+
{
|
|
87
|
+
name: "removeAttrs",
|
|
88
|
+
params: {
|
|
89
|
+
attrs: `(${removeAttrs.join("|")})`
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
] : []
|
|
93
|
+
]
|
|
94
|
+
}).data;
|
|
95
|
+
}
|
|
96
|
+
const svg = nodeHtmlParser.parse(svgContent).querySelector("svg");
|
|
97
|
+
if (!svg) {
|
|
98
|
+
throw new Error(`SVG file at path "${filePath}" does not contain an svg tag.`);
|
|
99
|
+
}
|
|
100
|
+
svg.tagName = "symbol";
|
|
101
|
+
svg.setAttribute("id", symbolId);
|
|
102
|
+
svg.removeAttribute("xmlns");
|
|
103
|
+
svg.removeAttribute("xmlns:xlink");
|
|
104
|
+
svg.removeAttribute("version");
|
|
105
|
+
const defs = svg.querySelector("defs");
|
|
106
|
+
if (defs) {
|
|
107
|
+
defs.childNodes.forEach((def) => definitions.push(def.toString()));
|
|
108
|
+
svg.removeChild(defs);
|
|
109
|
+
}
|
|
110
|
+
symbols.push(svg.toString());
|
|
111
|
+
})
|
|
112
|
+
);
|
|
113
|
+
const lines = [
|
|
114
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
115
|
+
'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0" height="0">'
|
|
116
|
+
];
|
|
117
|
+
if (definitions.length) {
|
|
118
|
+
lines.push(" <defs>", ...definitions.map((d) => ` ${d}`), " </defs>");
|
|
119
|
+
}
|
|
120
|
+
lines.push(...symbols.map((s) => ` ${s}`), "</svg>");
|
|
121
|
+
const content = lines.join("\n");
|
|
122
|
+
await writeIfChanged(spritePath, lines.join("\n"));
|
|
123
|
+
return content;
|
|
124
|
+
};
|
|
125
|
+
const svgoDefault = {
|
|
126
|
+
plugins: [
|
|
127
|
+
{
|
|
128
|
+
name: "preset-default",
|
|
129
|
+
params: {
|
|
130
|
+
overrides: {
|
|
131
|
+
removeViewBox: false,
|
|
132
|
+
convertColors: { currentColor: true }
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
"removeDimensions",
|
|
137
|
+
{
|
|
138
|
+
name: "removeAttrs",
|
|
139
|
+
params: { attrs: "(stroke-width|stroke-linecap|stroke-linejoin|class)" }
|
|
140
|
+
}
|
|
141
|
+
]
|
|
142
|
+
};
|
|
143
|
+
const inputConfigDefaults = {
|
|
144
|
+
pattern: "**/*.svg",
|
|
145
|
+
baseDir: "./",
|
|
146
|
+
prefix: "",
|
|
147
|
+
removeAttrs: [],
|
|
148
|
+
svgo: svgoDefault,
|
|
149
|
+
getSymbolId: (config) => config.prefix + config.matchPath.replace(/\.[^/.]+$/, "").replaceAll("/", "-").toLowerCase()
|
|
150
|
+
};
|
|
151
|
+
const stripUnusedDefaults = {
|
|
152
|
+
enabled: true,
|
|
153
|
+
srcInclude: "**/*.[jt]sx",
|
|
154
|
+
srcExclude: []
|
|
155
|
+
};
|
|
156
|
+
function svgSpritegen(config) {
|
|
157
|
+
const inputConfigs = Array.isArray(config.input) ? config.input : [config.input ?? inputConfigDefaults];
|
|
158
|
+
const inputConfigsResolved = inputConfigs.map((inputConfig) => {
|
|
159
|
+
const baseDir = path.resolve(process.cwd(), inputConfig.baseDir ?? inputConfigDefaults.baseDir);
|
|
160
|
+
return {
|
|
161
|
+
...inputConfigDefaults,
|
|
162
|
+
...inputConfig,
|
|
163
|
+
baseDir
|
|
164
|
+
};
|
|
165
|
+
});
|
|
166
|
+
const stripUnusedResolved = { ...stripUnusedDefaults };
|
|
167
|
+
if (typeof config.stripUnused === "object") {
|
|
168
|
+
Object.assign(stripUnusedResolved, config.stripUnused);
|
|
169
|
+
} else if (config.stripUnused === false) {
|
|
170
|
+
stripUnusedResolved.enabled = false;
|
|
171
|
+
}
|
|
172
|
+
const outputPath = path.resolve(process.cwd(), config.outputDir);
|
|
173
|
+
const spriteNameResolved = config.spriteFileName ?? "sprite.svg";
|
|
174
|
+
const typesFilePath = vite.normalizePath(path.join(outputPath, config.typesFileName ?? "types.ts"));
|
|
175
|
+
const spriteFilePath = vite.normalizePath(path.join(outputPath, spriteNameResolved));
|
|
176
|
+
const gitignoreFilePath = vite.normalizePath(path.join(outputPath, ".gitignore"));
|
|
177
|
+
const { srcInclude, srcExclude } = stripUnusedResolved;
|
|
178
|
+
const srcExcludeResolved = ["node_modules/**", srcExclude].flat().filter((e) => e !== null);
|
|
179
|
+
const srcFilter = vite.createFilter(srcInclude, srcExcludeResolved);
|
|
180
|
+
let watcher;
|
|
181
|
+
let allSvgFiles;
|
|
182
|
+
const referencedSvgFiles = /* @__PURE__ */ new Map();
|
|
183
|
+
let isBuild = false;
|
|
184
|
+
return {
|
|
185
|
+
name: "svg-spritegen",
|
|
186
|
+
enforce: "post",
|
|
187
|
+
configResolved(config2) {
|
|
188
|
+
isBuild = config2.command === "build";
|
|
189
|
+
},
|
|
190
|
+
async buildStart() {
|
|
191
|
+
allSvgFiles = await buildSvgMap(inputConfigsResolved);
|
|
192
|
+
await writeTypes(typesFilePath, allSvgFiles);
|
|
193
|
+
if (config.gitignore !== false) {
|
|
194
|
+
await writeGitignore(gitignoreFilePath, "sprite.svg", "types.ts");
|
|
195
|
+
}
|
|
196
|
+
if (isBuild) {
|
|
197
|
+
if (stripUnusedResolved.enabled) {
|
|
198
|
+
await writeIfChanged(spriteFilePath);
|
|
199
|
+
} else {
|
|
200
|
+
await writeSprite(spriteFilePath, allSvgFiles);
|
|
201
|
+
}
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
await writeSprite(spriteFilePath, allSvgFiles);
|
|
205
|
+
const onWatch = (path2) => {
|
|
206
|
+
if (path2 === spriteFilePath) return;
|
|
207
|
+
buildSvgMap(inputConfigsResolved).then((newAllSvgFiles) => {
|
|
208
|
+
writeSprite(spriteFilePath, newAllSvgFiles);
|
|
209
|
+
});
|
|
210
|
+
};
|
|
211
|
+
const inputPaths = inputConfigsResolved.map((config2) => config2.baseDir);
|
|
212
|
+
watcher = chokidar.watch(inputPaths, { ignoreInitial: true }).on("add", onWatch).on("change", onWatch).on("unlink", onWatch);
|
|
213
|
+
},
|
|
214
|
+
moduleParsed(info) {
|
|
215
|
+
var _a;
|
|
216
|
+
if (!isBuild || !stripUnusedResolved.enabled || !srcFilter(info.id) || !info.code) return;
|
|
217
|
+
const matches = info.code.matchAll(/(?:(?:name)|(?:iconName)|(?:icon)): "(?<icon>.+?)"/g);
|
|
218
|
+
for (const match of matches) {
|
|
219
|
+
const icon = (_a = match.groups) == null ? void 0 : _a.icon;
|
|
220
|
+
if (!icon || referencedSvgFiles.has(icon)) continue;
|
|
221
|
+
const svgPath = allSvgFiles.get(icon);
|
|
222
|
+
if (!svgPath) continue;
|
|
223
|
+
referencedSvgFiles.set(icon, svgPath);
|
|
224
|
+
}
|
|
225
|
+
},
|
|
226
|
+
async generateBundle(_options, bundle) {
|
|
227
|
+
if (stripUnusedResolved.enabled) {
|
|
228
|
+
const spriteContent = await writeSprite(spriteFilePath, referencedSvgFiles);
|
|
229
|
+
Object.values(bundle).forEach((file) => {
|
|
230
|
+
if (file.type === "asset" && file.name === spriteNameResolved) {
|
|
231
|
+
file.source = spriteContent;
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
},
|
|
236
|
+
async closeBundle() {
|
|
237
|
+
await (watcher == null ? void 0 : watcher.close());
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
exports.svgSpritegen = svgSpritegen;
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { watch } from "chokidar";
|
|
3
|
+
import { normalizePath, createFilter } from "vite";
|
|
4
|
+
import fastGlob from "fast-glob";
|
|
5
|
+
import { promises } from "node:fs";
|
|
6
|
+
import { parse } from "node-html-parser";
|
|
7
|
+
import { optimize } from "svgo";
|
|
8
|
+
const buildSvgMap = async (inputConfigs) => {
|
|
9
|
+
const svgMap = /* @__PURE__ */ new Map();
|
|
10
|
+
for (const inputConfig of inputConfigs) {
|
|
11
|
+
const { pattern, baseDir, getSymbolId } = inputConfig;
|
|
12
|
+
const matchPaths = await fastGlob(pattern, { cwd: baseDir });
|
|
13
|
+
for (const matchPath of matchPaths) {
|
|
14
|
+
const resolvedInputConfig = {
|
|
15
|
+
...inputConfig,
|
|
16
|
+
matchPath,
|
|
17
|
+
filePath: path.join(baseDir, matchPath)
|
|
18
|
+
};
|
|
19
|
+
const symbolId = getSymbolId(resolvedInputConfig);
|
|
20
|
+
if (svgMap.has(symbolId)) {
|
|
21
|
+
console.log(
|
|
22
|
+
`Duplicate SVG symbol id "${symbolId}. Symbol ids should be unique across all inputs."`
|
|
23
|
+
);
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
svgMap.set(symbolId, { ...resolvedInputConfig, symbolId });
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return svgMap;
|
|
30
|
+
};
|
|
31
|
+
const writeIfChanged = async (filePath, content) => {
|
|
32
|
+
try {
|
|
33
|
+
const currentContent = await promises.readFile(filePath, "utf8");
|
|
34
|
+
if (content && currentContent !== content) {
|
|
35
|
+
await promises.writeFile(filePath, content, "utf8");
|
|
36
|
+
}
|
|
37
|
+
} catch (e) {
|
|
38
|
+
await promises.writeFile(filePath, content ?? "", "utf8");
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
const writeTypes = async (filePath, svgMap) => {
|
|
42
|
+
const iconNames = [...svgMap.keys()];
|
|
43
|
+
const content = [
|
|
44
|
+
"/* eslint-disable */",
|
|
45
|
+
"",
|
|
46
|
+
"// This file is autogenerated. Do not commit to source control.",
|
|
47
|
+
"",
|
|
48
|
+
"export type IconName = (typeof iconNames)[number];",
|
|
49
|
+
"",
|
|
50
|
+
"export const iconNames = [",
|
|
51
|
+
...iconNames.map((name) => ` '${name}',`),
|
|
52
|
+
"] as const;",
|
|
53
|
+
""
|
|
54
|
+
].join("\n");
|
|
55
|
+
await writeIfChanged(filePath, content);
|
|
56
|
+
};
|
|
57
|
+
const writeGitignore = async (filePath, spriteName, typesName) => {
|
|
58
|
+
const content = ["# svg spritegen", spriteName, typesName].join("\n");
|
|
59
|
+
try {
|
|
60
|
+
const currentContent = await promises.readFile(filePath, "utf8");
|
|
61
|
+
if (currentContent.includes(content)) {
|
|
62
|
+
return;
|
|
63
|
+
} else {
|
|
64
|
+
await promises.writeFile(filePath, currentContent + "\n" + content, "utf8");
|
|
65
|
+
}
|
|
66
|
+
} catch (e) {
|
|
67
|
+
await promises.writeFile(filePath, content, "utf8");
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
const writeSprite = async (spritePath, svgMap) => {
|
|
71
|
+
const symbols = [];
|
|
72
|
+
const definitions = [];
|
|
73
|
+
await Promise.all(
|
|
74
|
+
[...svgMap.values()].map(async (inputConfig) => {
|
|
75
|
+
const { svgo, removeAttrs, symbolId, filePath } = inputConfig;
|
|
76
|
+
if (spritePath === filePath) return;
|
|
77
|
+
let svgContent = await promises.readFile(filePath, "utf8");
|
|
78
|
+
if (svgo !== false) {
|
|
79
|
+
svgContent = optimize(svgContent, {
|
|
80
|
+
...svgo,
|
|
81
|
+
plugins: [
|
|
82
|
+
...svgo.plugins ?? [],
|
|
83
|
+
...removeAttrs.length ? [
|
|
84
|
+
{
|
|
85
|
+
name: "removeAttrs",
|
|
86
|
+
params: {
|
|
87
|
+
attrs: `(${removeAttrs.join("|")})`
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
] : []
|
|
91
|
+
]
|
|
92
|
+
}).data;
|
|
93
|
+
}
|
|
94
|
+
const svg = parse(svgContent).querySelector("svg");
|
|
95
|
+
if (!svg) {
|
|
96
|
+
throw new Error(`SVG file at path "${filePath}" does not contain an svg tag.`);
|
|
97
|
+
}
|
|
98
|
+
svg.tagName = "symbol";
|
|
99
|
+
svg.setAttribute("id", symbolId);
|
|
100
|
+
svg.removeAttribute("xmlns");
|
|
101
|
+
svg.removeAttribute("xmlns:xlink");
|
|
102
|
+
svg.removeAttribute("version");
|
|
103
|
+
const defs = svg.querySelector("defs");
|
|
104
|
+
if (defs) {
|
|
105
|
+
defs.childNodes.forEach((def) => definitions.push(def.toString()));
|
|
106
|
+
svg.removeChild(defs);
|
|
107
|
+
}
|
|
108
|
+
symbols.push(svg.toString());
|
|
109
|
+
})
|
|
110
|
+
);
|
|
111
|
+
const lines = [
|
|
112
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
113
|
+
'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0" height="0">'
|
|
114
|
+
];
|
|
115
|
+
if (definitions.length) {
|
|
116
|
+
lines.push(" <defs>", ...definitions.map((d) => ` ${d}`), " </defs>");
|
|
117
|
+
}
|
|
118
|
+
lines.push(...symbols.map((s) => ` ${s}`), "</svg>");
|
|
119
|
+
const content = lines.join("\n");
|
|
120
|
+
await writeIfChanged(spritePath, lines.join("\n"));
|
|
121
|
+
return content;
|
|
122
|
+
};
|
|
123
|
+
const svgoDefault = {
|
|
124
|
+
plugins: [
|
|
125
|
+
{
|
|
126
|
+
name: "preset-default",
|
|
127
|
+
params: {
|
|
128
|
+
overrides: {
|
|
129
|
+
removeViewBox: false,
|
|
130
|
+
convertColors: { currentColor: true }
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
"removeDimensions",
|
|
135
|
+
{
|
|
136
|
+
name: "removeAttrs",
|
|
137
|
+
params: { attrs: "(stroke-width|stroke-linecap|stroke-linejoin|class)" }
|
|
138
|
+
}
|
|
139
|
+
]
|
|
140
|
+
};
|
|
141
|
+
const inputConfigDefaults = {
|
|
142
|
+
pattern: "**/*.svg",
|
|
143
|
+
baseDir: "./",
|
|
144
|
+
prefix: "",
|
|
145
|
+
removeAttrs: [],
|
|
146
|
+
svgo: svgoDefault,
|
|
147
|
+
getSymbolId: (config) => config.prefix + config.matchPath.replace(/\.[^/.]+$/, "").replaceAll("/", "-").toLowerCase()
|
|
148
|
+
};
|
|
149
|
+
const stripUnusedDefaults = {
|
|
150
|
+
enabled: true,
|
|
151
|
+
srcInclude: "**/*.[jt]sx",
|
|
152
|
+
srcExclude: []
|
|
153
|
+
};
|
|
154
|
+
function svgSpritegen(config) {
|
|
155
|
+
const inputConfigs = Array.isArray(config.input) ? config.input : [config.input ?? inputConfigDefaults];
|
|
156
|
+
const inputConfigsResolved = inputConfigs.map((inputConfig) => {
|
|
157
|
+
const baseDir = path.resolve(process.cwd(), inputConfig.baseDir ?? inputConfigDefaults.baseDir);
|
|
158
|
+
return {
|
|
159
|
+
...inputConfigDefaults,
|
|
160
|
+
...inputConfig,
|
|
161
|
+
baseDir
|
|
162
|
+
};
|
|
163
|
+
});
|
|
164
|
+
const stripUnusedResolved = { ...stripUnusedDefaults };
|
|
165
|
+
if (typeof config.stripUnused === "object") {
|
|
166
|
+
Object.assign(stripUnusedResolved, config.stripUnused);
|
|
167
|
+
} else if (config.stripUnused === false) {
|
|
168
|
+
stripUnusedResolved.enabled = false;
|
|
169
|
+
}
|
|
170
|
+
const outputPath = path.resolve(process.cwd(), config.outputDir);
|
|
171
|
+
const spriteNameResolved = config.spriteFileName ?? "sprite.svg";
|
|
172
|
+
const typesFilePath = normalizePath(path.join(outputPath, config.typesFileName ?? "types.ts"));
|
|
173
|
+
const spriteFilePath = normalizePath(path.join(outputPath, spriteNameResolved));
|
|
174
|
+
const gitignoreFilePath = normalizePath(path.join(outputPath, ".gitignore"));
|
|
175
|
+
const { srcInclude, srcExclude } = stripUnusedResolved;
|
|
176
|
+
const srcExcludeResolved = ["node_modules/**", srcExclude].flat().filter((e) => e !== null);
|
|
177
|
+
const srcFilter = createFilter(srcInclude, srcExcludeResolved);
|
|
178
|
+
let watcher;
|
|
179
|
+
let allSvgFiles;
|
|
180
|
+
const referencedSvgFiles = /* @__PURE__ */ new Map();
|
|
181
|
+
let isBuild = false;
|
|
182
|
+
return {
|
|
183
|
+
name: "svg-spritegen",
|
|
184
|
+
enforce: "post",
|
|
185
|
+
configResolved(config2) {
|
|
186
|
+
isBuild = config2.command === "build";
|
|
187
|
+
},
|
|
188
|
+
async buildStart() {
|
|
189
|
+
allSvgFiles = await buildSvgMap(inputConfigsResolved);
|
|
190
|
+
await writeTypes(typesFilePath, allSvgFiles);
|
|
191
|
+
if (config.gitignore !== false) {
|
|
192
|
+
await writeGitignore(gitignoreFilePath, "sprite.svg", "types.ts");
|
|
193
|
+
}
|
|
194
|
+
if (isBuild) {
|
|
195
|
+
if (stripUnusedResolved.enabled) {
|
|
196
|
+
await writeIfChanged(spriteFilePath);
|
|
197
|
+
} else {
|
|
198
|
+
await writeSprite(spriteFilePath, allSvgFiles);
|
|
199
|
+
}
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
await writeSprite(spriteFilePath, allSvgFiles);
|
|
203
|
+
const onWatch = (path2) => {
|
|
204
|
+
if (path2 === spriteFilePath) return;
|
|
205
|
+
buildSvgMap(inputConfigsResolved).then((newAllSvgFiles) => {
|
|
206
|
+
writeSprite(spriteFilePath, newAllSvgFiles);
|
|
207
|
+
});
|
|
208
|
+
};
|
|
209
|
+
const inputPaths = inputConfigsResolved.map((config2) => config2.baseDir);
|
|
210
|
+
watcher = watch(inputPaths, { ignoreInitial: true }).on("add", onWatch).on("change", onWatch).on("unlink", onWatch);
|
|
211
|
+
},
|
|
212
|
+
moduleParsed(info) {
|
|
213
|
+
var _a;
|
|
214
|
+
if (!isBuild || !stripUnusedResolved.enabled || !srcFilter(info.id) || !info.code) return;
|
|
215
|
+
const matches = info.code.matchAll(/(?:(?:name)|(?:iconName)|(?:icon)): "(?<icon>.+?)"/g);
|
|
216
|
+
for (const match of matches) {
|
|
217
|
+
const icon = (_a = match.groups) == null ? void 0 : _a.icon;
|
|
218
|
+
if (!icon || referencedSvgFiles.has(icon)) continue;
|
|
219
|
+
const svgPath = allSvgFiles.get(icon);
|
|
220
|
+
if (!svgPath) continue;
|
|
221
|
+
referencedSvgFiles.set(icon, svgPath);
|
|
222
|
+
}
|
|
223
|
+
},
|
|
224
|
+
async generateBundle(_options, bundle) {
|
|
225
|
+
if (stripUnusedResolved.enabled) {
|
|
226
|
+
const spriteContent = await writeSprite(spriteFilePath, referencedSvgFiles);
|
|
227
|
+
Object.values(bundle).forEach((file) => {
|
|
228
|
+
if (file.type === "asset" && file.name === spriteNameResolved) {
|
|
229
|
+
file.source = spriteContent;
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
},
|
|
234
|
+
async closeBundle() {
|
|
235
|
+
await (watcher == null ? void 0 : watcher.close());
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
export {
|
|
240
|
+
svgSpritegen
|
|
241
|
+
};
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { FilterPattern } from 'vite';
|
|
2
|
+
import { Config as SvgoConfig } from 'svgo';
|
|
3
|
+
export interface InputConfig {
|
|
4
|
+
pattern?: string;
|
|
5
|
+
baseDir?: string;
|
|
6
|
+
prefix?: string;
|
|
7
|
+
getSymbolId?: (config: Omit<ResolvedInputConfig, 'symbolId'>) => string;
|
|
8
|
+
removeAttrs?: string[];
|
|
9
|
+
svgo?: SvgoConfig | false;
|
|
10
|
+
}
|
|
11
|
+
export interface ResolvedInputConfig extends Required<InputConfig> {
|
|
12
|
+
symbolId: string;
|
|
13
|
+
matchPath: string;
|
|
14
|
+
filePath: string;
|
|
15
|
+
}
|
|
16
|
+
export type SvgMap = Map<string, ResolvedInputConfig>;
|
|
17
|
+
export interface StripUnusedConfig {
|
|
18
|
+
enabled?: boolean;
|
|
19
|
+
srcInclude?: FilterPattern;
|
|
20
|
+
srcExclude?: FilterPattern;
|
|
21
|
+
}
|
|
22
|
+
export interface PluginConfig {
|
|
23
|
+
outputDir: string;
|
|
24
|
+
input?: InputConfig | InputConfig[];
|
|
25
|
+
stripUnused?: boolean | StripUnusedConfig;
|
|
26
|
+
typesFileName?: string;
|
|
27
|
+
spriteFileName?: string;
|
|
28
|
+
gitignore?: boolean;
|
|
29
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const writeGitignore: (filePath: string, spriteName: string, typesName: string) => Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const writeIfChanged: (filePath: string, content?: string) => Promise<void>;
|
package/package.json
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "vite-plugin-svg-spritegen",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Vite plugin that generates an svg spritesheet, optionally removing unused svg files.",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"module": "./dist/index.mjs",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"keywords": [
|
|
9
|
+
"icons",
|
|
10
|
+
"spritesheet",
|
|
11
|
+
"vite",
|
|
12
|
+
"plugin",
|
|
13
|
+
"generator",
|
|
14
|
+
"svg"
|
|
15
|
+
],
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"import": {
|
|
19
|
+
"import": "./dist/index.mjs",
|
|
20
|
+
"default": "./dist/index.mjs",
|
|
21
|
+
"types": "./dist/index.d.ts"
|
|
22
|
+
},
|
|
23
|
+
"require": {
|
|
24
|
+
"import": "./dist/index.js",
|
|
25
|
+
"require": "./dist/index.js",
|
|
26
|
+
"default": "./dist/index.js",
|
|
27
|
+
"types": "./dist/index.d.ts"
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"start": "npm run build:watch",
|
|
33
|
+
"build": "vite build & tsc --emitDeclarationOnly --declaration",
|
|
34
|
+
"build:watch": "vite build --watch & tsc --emitDeclarationOnly --declaration -w",
|
|
35
|
+
"lint": "eslint . --fix"
|
|
36
|
+
},
|
|
37
|
+
"author": "",
|
|
38
|
+
"license": "ISC",
|
|
39
|
+
"repository": {
|
|
40
|
+
"type": "git",
|
|
41
|
+
"url": "git+https://github.com/jayalfredprufrock/vite-plugin-svg-spritegen.git"
|
|
42
|
+
},
|
|
43
|
+
"bugs": {
|
|
44
|
+
"url": "https://github.com/jayalfredprufrock/vite-plugin-svg-spritegen/issues"
|
|
45
|
+
},
|
|
46
|
+
"files": [
|
|
47
|
+
"dist"
|
|
48
|
+
],
|
|
49
|
+
"homepage": "https://github.com/jayalfredprufrock/vite-plugin-svg-spritegen#readme",
|
|
50
|
+
"dependencies": {
|
|
51
|
+
"chokidar": "^3.6.0",
|
|
52
|
+
"fast-glob": "^3.3.2",
|
|
53
|
+
"node-html-parser": "^6.1.13",
|
|
54
|
+
"svgo": "^3.3.2"
|
|
55
|
+
},
|
|
56
|
+
"peerDependencies": {
|
|
57
|
+
"vite": ">=5.2.0"
|
|
58
|
+
},
|
|
59
|
+
"devDependencies": {
|
|
60
|
+
"@types/node": "^20.14.12",
|
|
61
|
+
"@typescript-eslint/eslint-plugin": "^7.7.0",
|
|
62
|
+
"@typescript-eslint/parser": "^7.7.0",
|
|
63
|
+
"eslint": "^8.57.0",
|
|
64
|
+
"eslint-config-prettier": "^9.1.0",
|
|
65
|
+
"eslint-import-resolver-typescript": "^3.5.2",
|
|
66
|
+
"eslint-plugin-import": "^2.26.0",
|
|
67
|
+
"eslint-plugin-prettier": "^5.1.3",
|
|
68
|
+
"prettier": "^3.2.5",
|
|
69
|
+
"typescript": "^5.4.5",
|
|
70
|
+
"vite": "^5.2.11"
|
|
71
|
+
}
|
|
72
|
+
}
|