Skip to content

Commit ad9dedf

Browse files
committed
feat(Svg): add new parameter for the_icon to define if SVG is displayed as sprite or plain svg
1 parent ce60c30 commit ad9dedf

7 files changed

Lines changed: 280 additions & 29 deletions

File tree

‎config/plugins.js‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const BundleAnalyzerPlugin =
1313
const WebpackThemeJsonPlugin = require('./webpack-theme-json-plugin');
1414
const WatchedGlobEntriesPlugin = require('webpack-watched-glob-entries-plugin');
1515
const SpriteHashPlugin = require('./webpack-sprite-hash-plugin');
16+
const WebpackIconFilesPlugin = require('./webpack-icon-files-plugin');
1617

1718
module.exports = {
1819
get(mode) {
@@ -21,7 +22,14 @@ module.exports = {
2122
watch: mode !== 'production',
2223
}),
2324
new SpriteHashPlugin(),
24-
new CleanWebpackPlugin(),
25+
new WebpackIconFilesPlugin({
26+
sourcePath: 'src/img/icons',
27+
outputPath: 'dist/images',
28+
silence: true,
29+
}),
30+
new CleanWebpackPlugin({
31+
cleanOnceBeforeBuildPatterns: ['**/*', '!images', '!images/**'],
32+
}),
2533
new ESLintPlugin({
2634
overrideConfigFile: path.resolve(__dirname, '../.eslintrc'),
2735
context: path.resolve(__dirname, '../src/js'),

‎config/svgo.config.js‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,9 @@ module.exports = {
22
plugins: [
33
{
44
name: 'preset-default',
5-
params: {
6-
overrides: {
7-
// Disable a plugin included by default that you don't want (false)
8-
removeViewBox: false,
9-
},
10-
},
115
},
12-
// Plugins that are not in the "preset-default" and that you want to activate
136
'removeTitle',
147
'convertStyleToAttrs',
8+
'prefixIds',
159
],
16-
}
10+
};
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
const fs = require('fs');
2+
const path = require('path');
3+
const { optimize } = require('svgo');
4+
const svgoConfig = require('./svgo.config');
5+
6+
/**
7+
* Webpack plugin that writes optimized standalone SVG files from icon sources.
8+
* Sprite sheets under dist/icons are unchanged; this mirrors src/img/icons/** into dist/images/**.
9+
*
10+
* @class WebpackIconFilesPlugin
11+
*/
12+
class WebpackIconFilesPlugin {
13+
/**
14+
* @param {Object} [options={}] Plugin options.
15+
* @param {string} [options.sourcePath='src/img/icons'] Source icons directory.
16+
* @param {string} [options.outputPath='dist/images'] Output directory (subfolders preserved).
17+
* @param {boolean} [options.silence=false] Suppress console output.
18+
*/
19+
constructor(options = {}) {
20+
this.options = {
21+
sourcePath: 'src/img/icons',
22+
outputPath: 'dist/images',
23+
silence: false,
24+
...options,
25+
};
26+
}
27+
28+
/**
29+
* @param {string} level Log level.
30+
* @param {...any} args Log arguments.
31+
*/
32+
log(level, ...args) {
33+
if (!this.options.silence) {
34+
console[level](...args);
35+
}
36+
}
37+
38+
/**
39+
* @param {string} directory Directory to scan.
40+
* @return {string[]} Absolute paths to SVG files.
41+
*/
42+
collectSvgFiles(directory) {
43+
const files = [];
44+
45+
if (!fs.existsSync(directory)) {
46+
return files;
47+
}
48+
49+
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
50+
const fullPath = path.join(directory, entry.name);
51+
52+
if (entry.isDirectory()) {
53+
files.push(...this.collectSvgFiles(fullPath));
54+
continue;
55+
}
56+
57+
if (entry.name.endsWith('.svg')) {
58+
files.push(fullPath);
59+
}
60+
}
61+
62+
return files;
63+
}
64+
65+
/**
66+
* @param {import('webpack').Compiler} compiler Webpack compiler.
67+
*/
68+
apply(compiler) {
69+
compiler.hooks.afterEmit.tapAsync(
70+
'WebpackIconFilesPlugin',
71+
(compilation, callback) => {
72+
const context = compiler.options.context;
73+
const sourceDir = path.resolve(context, this.options.sourcePath);
74+
const outputDir = path.resolve(context, this.options.outputPath);
75+
const svgFiles = this.collectSvgFiles(sourceDir);
76+
77+
if (svgFiles.length === 0) {
78+
callback();
79+
return;
80+
}
81+
82+
let written = 0;
83+
84+
for (const sourceFile of svgFiles) {
85+
const relativePath = path.relative(sourceDir, sourceFile);
86+
const destFile = path.join(outputDir, relativePath);
87+
88+
fs.mkdirSync(path.dirname(destFile), { recursive: true });
89+
90+
const input = fs.readFileSync(sourceFile, 'utf8');
91+
const result = optimize(input, {
92+
path: sourceFile,
93+
...svgoConfig,
94+
});
95+
96+
if (result.error) {
97+
console.warn(
98+
`WebpackIconFilesPlugin: SVGO failed for ${relativePath}: ${result.error}`
99+
);
100+
continue;
101+
}
102+
103+
fs.writeFileSync(destFile, result.data);
104+
written++;
105+
}
106+
107+
this.log(
108+
'log',
109+
`WebpackIconFilesPlugin: Wrote ${written} optimized SVG(s) to ${this.options.outputPath}`
110+
);
111+
112+
callback();
113+
}
114+
);
115+
}
116+
}
117+
118+
module.exports = WebpackIconFilesPlugin;

‎config/webpack.common.js‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ module.exports = {
1010
path: path.resolve(__dirname, '../dist'),
1111
publicPath: '',
1212
assetModuleFilename: 'assets/[hash][ext][query]',
13-
clean: true,
1413
},
1514
optimization: {
1615
minimizer: [

‎grumphp.yml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@ grumphp:
1313
- "beapi.xyz"
1414
- "lndo.site"
1515
whitelist_patterns: []
16+
ignore_patterns:
17+
- /^node_modules\//
18+
- /^config\//
19+
- /^dist\//
1620
triggered_by: ['php', 'js', 'scss', 'css']
1721
regexp_type: G
1822
phplint:

‎inc/Helpers/Svg.php‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,28 +7,30 @@
77
* @usage BEA\Theme\Framework\Helpers\Svg\get_the_icon( 'like' );
88
*
99
* @param string $icon_class
10-
* @param array $additionnal_classes
10+
* @param array $additionnal_classes
11+
* @param bool $is_sprite
1112
*
1213
* @return string
1314
*/
14-
function get_the_icon( string $icon_class, $additionnal_classes = [] ): string {
15+
function get_the_icon( string $icon_class, $additionnal_classes = [], bool $is_sprite = true ): string {
1516
/**
1617
* @var Svg $svg
1718
*/
1819
$svg = \BEA\Theme\Framework\Framework::get_container()->get_service( 'svg' );
19-
return false !== $svg ? $svg->get_the_icon( $icon_class, $additionnal_classes ) : '';
20+
return false !== $svg ? $svg->get_the_icon( $icon_class, $additionnal_classes, $is_sprite ) : '';
2021
}
2122

2223
/**
2324
* @usage BEA\Theme\Framework\Helpers\Svg\the_icon( 'like' );
2425
*
2526
* @param string $icon_class
2627
* @param array $additionnal_classes
28+
* @param bool $is_sprite
2729
*/
28-
function the_icon( string $icon_class, $additionnal_classes = [] ): void {
30+
function the_icon( string $icon_class, $additionnal_classes = [], bool $is_sprite = true ): void {
2931
/**
3032
* @var Svg $svg
3133
*/
3234
$svg = \BEA\Theme\Framework\Framework::get_container()->get_service( 'svg' );
33-
false !== $svg ? $svg->the_icon( $icon_class, $additionnal_classes ) : '';
35+
false !== $svg ? $svg->the_icon( $icon_class, $additionnal_classes, $is_sprite ) : '';
3436
}

0 commit comments

Comments
 (0)