punchcutter 2.1.1 → 2.1.2
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/lib/svgMin.js +42 -7
- package/package.json +1 -1
package/lib/svgMin.js
CHANGED
|
@@ -1,14 +1,48 @@
|
|
|
1
|
-
const
|
|
1
|
+
const sharp = require('sharp');
|
|
2
2
|
const {optimize} = require('svgo');
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
*
|
|
6
6
|
* @param {string} data
|
|
7
|
+
* @param {object} options
|
|
7
8
|
* @returns {Promise}
|
|
8
9
|
*/
|
|
9
|
-
module.exports = (data) =>
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
module.exports = async (data, options = {minifyRasterImages: true}) => {
|
|
11
|
+
let result = data;
|
|
12
|
+
|
|
13
|
+
if (options.minifyRasterImages) {
|
|
14
|
+
// Match <image> elements with xlink:href containing PNG, JPEG, or GIF base64 data
|
|
15
|
+
const imageTagRegex =
|
|
16
|
+
/<image\b[^>]*?xlink:href="(data:image\/(png|jpeg|jpg|gif);base64,[\s\S]+?)"[^>]*?>/gm;
|
|
17
|
+
let matches = [...result.matchAll(imageTagRegex)];
|
|
18
|
+
|
|
19
|
+
for (const match of matches) {
|
|
20
|
+
let fullMatch = match[0]; // The entire <image> tag
|
|
21
|
+
let imageDataUri = match[1]; // Extracted image data URI
|
|
22
|
+
let imageType = match[2]; // Extracted format (png, jpeg, jpg, gif)
|
|
23
|
+
|
|
24
|
+
// Extract the base64 data and remove any whitespace/newlines
|
|
25
|
+
let base64Image = imageDataUri
|
|
26
|
+
.replace(/^data:image\/(png|jpeg|jpg|gif);base64,/, '')
|
|
27
|
+
.replace(/\s+/g, '');
|
|
28
|
+
let imageBuffer = Buffer.from(base64Image, 'base64');
|
|
29
|
+
|
|
30
|
+
// Convert PNG, JPEG, or GIF to WebP using sharp
|
|
31
|
+
let webpBuffer = await sharp(imageBuffer).webp().toBuffer();
|
|
32
|
+
let base64Webp = webpBuffer.toString('base64');
|
|
33
|
+
|
|
34
|
+
// Replace image data URI with WebP data URI inside the <image> tag
|
|
35
|
+
let webpDataUri = `data:image/webp;base64,${base64Webp}`;
|
|
36
|
+
let updatedImageTag = fullMatch.replace(imageDataUri, webpDataUri);
|
|
37
|
+
|
|
38
|
+
// Update the SVG content
|
|
39
|
+
result = result.replace(fullMatch, updatedImageTag);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Optimize using SVGO
|
|
44
|
+
result = (
|
|
45
|
+
await optimize(result, {
|
|
12
46
|
plugins: [
|
|
13
47
|
{
|
|
14
48
|
name: 'preset-default',
|
|
@@ -19,7 +53,8 @@ module.exports = (data) =>
|
|
|
19
53
|
}
|
|
20
54
|
}
|
|
21
55
|
]
|
|
22
|
-
})
|
|
56
|
+
})
|
|
57
|
+
).data;
|
|
23
58
|
|
|
24
|
-
|
|
25
|
-
|
|
59
|
+
return result;
|
|
60
|
+
};
|