Testé fonctionnel Webpack Encore v1.1.2 (tournant sous Webpack v5.34.0).
- Image Webpack Loader – un module d’optimisation des sources « images » pour Webpack. Polyvalent, il prend en charge les formats JPEG, PNG, SVG, GIF et propose même de convertir des JPEGs et des PNGs au format WEBP!
- SVG Optimizer is a Node.js-based tool for optimizing SVG vector graphics files.
- Asset Modules is a type of module that allows one to use asset files (fonts, icons, etc) without configuring additional loaders.
- Utiliser SVGO avec la méthode .addRule() de Webpack Encore.
- What is the benefit of stripping viewBox? Short answer: there’s NO benefit doing that!
Installer image-webpack-loader:
1 |
npm install image-webpack-loader --save-dev |
Dans webpack.config.js
:
Attention au chemin renseigné pour la méthode .setOutputPath()
: c’est là que vos SVG optimisés seront consignés.
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 |
// directory where compiled assets will be stored .setOutputPath('web/build/') [..] // https://webpack.js.org/guides/asset-modules/#custom-output-filename .addRule({ test: /\.svg$/, type: 'asset/resource', use: [ // https://www.npmjs.com/package/image-webpack-loader // https://github.com/tcoopman/image-webpack-loader { loader: 'image-webpack-loader', options: { // https://github.com/svg/svgo svgo: { // configFile: './svgo.config.js' removeViewBox: true, } } } ] }) ; // export the final config module.exports = Encore.getWebpackConfig(); |
Dans assets/app.js
1 |
import svgIcon from './images/icons/film.svg'; |
Solution alternative avec le module svgo-loader (mais ne prend en charge que le format SVG):
Dans webpack.config.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 |
// directory where compiled assets will be stored .setOutputPath('web/build/') [..] // https://webpack.js.org/guides/asset-modules/#custom-output-filename .addRule({ test: /\.svg$/, type: 'asset/resource', use: [ // https://github.com/svg/svgo-loader { loader: 'svgo-loader', options: { // configFile: './svgo.config.js' removeViewBox: true } } ] }) ; // export the final config module.exports = Encore.getWebpackConfig(); |