Movatterモバイル変換


[0]ホーム

URL:


webpack logo
ag grid
ag charts

SvgChunkWebpackPlugin

Disclaimer: SvgChunkWebpackPlugin is a third-party package maintained by community members, it potentially does not have the same support, security policy or license as webpack, and it is not maintained by webpack.

GitHub Workflow Status (branch)Coverage StatusNpm downloads

Thesvg-chunk-webpack-plugin creates optimized SVG sprites, according to Webpack's entrypoints. Each sprite contains only the SVG dependencies listed on its entrypoints to improved code splitting, even on SVG files.

The plugin includes the popularSVGO package to generates clean and optimized SVG sprites.

Code splitting is the key to deliver files without any content that is unused by the pages. It already exists for CSS, Javascript and now for SVG files with this plugin.

When to use this plugin

On multiple page application, each pages must includes only its necessary dependencies. In other words, it must include only the SVG files imported by its entrypoint and all its dependencies.

With reusable components, SVGs are often duplicated on all the project. Now, you can create a global SVG library and every Javascript files can easily import any SVG from this library. Entrypoint dependencies are automatically updated, thanks to the Webpack compilation.

When you work with SVGs exported by design softwares, like Sketch or Illustrator, their source code is never optimized and often contains comments, CSS classes which can create conflicts between them. The plugin automatically cleans all SVGs before creating the sprite.

Zero config

The plugin works without configuration with already the optimized settings. For advanced usage, see the sectionusing configuration.

Installation

The plugin is available as a package with the name ofsvg-chunk-webpack-plugin onnpm andGithub.

npminstall svg-chunk-webpack-plugin --save-dev
yarnadd svg-chunk-webpack-plugin --dev

[!WARNING]Pluginsvg-chunk-webpack-plugin@5 is ESM only.[!NOTE]Minimum supportedNode.js version is16.20.0 and Webpack>=5.10.3.

Example

The project includes a minimalist example in the./example directory. Run thenpm run build:example command to execute the Webpack example and see the plugin's implementation in action.

Basic usage

The plugin will generate one SVG sprite for each entrypoints. Sprites are built in the output path directory with all the other assets. Each sprite filename is composed with its entrypoint name (in the example below, that would behome.svg).

First, let's add the loader and the plugin to the Webpack configuration.

[!WARNING]The loader and the plugin need to works together.

webpack.config.js

import SvgChunkWebpackPluginfrom'svg-chunk-webpack-plugin';exportdefault{  module:{    rules:[{        test:/\.svg$/,        use:[{            loader: SvgChunkWebpackPlugin.loader}]}]},  plugins:[newSvgChunkWebpackPlugin()]};

[!NOTE]For more flexibility and better performance, inline SVG files are better. Fewer HTTP requests, CSS properties to change the style, no flickering during the page load.

Then, include the sprite in the wanted pages (we use Twig in the following example).

home.html.twig

{{ include 'home.svg' }}

Finally, use the SVG with the<use> tag, like the following example. Replace<svg_name> by the SVG name (without the extension).

home.html.twig

<svg><usehref="#<svg_name>"></use></svg>

Using a configuration

The loader and the plugin accepts configuration to override the default behavior.

Loader

The loader configuration allow to personalize the SVGO configuration. SVGO optimization is executed during the loader process to optimize build performance.

configFile

Type:

typeconfigFile=string|boolean;

Default:path.resolve(opts.root, 'svgo.config.js')

Tells the loader whether to load the customSVGO configuration. Custom configuration can be disabled withconfigFile: false.

webpack.config.js

exportdefault{  module:{    rules:[{        test:/\.svg$/,        loader: SvgChunkWebpackPlugin.loader,        options:{          configFile:'./path/svgo.config.js'}}]}};

SVGO custom configuration

SVGO have a default preset to optimize SVG files. Seehow to configure svgo for details.

svgo.config.js

exportdefault{  multipass:true,  plugins:[{      name:'preset-default',      params:{        overrides:{          inlineStyles:{            onlyMatchedOnce:false},          removeViewBox:false}}},{      name:'convertStyleToAttrs'}]};

Plugin

The plugin configuration allow to personalize sprite settings.

filename

Type:

typefilename=string;

Default:'[name].svg'

Tells the plugin whether to personalize the default sprite filename. The placeholder[name] is automatically replaced by entrypoints names.

webpack.config.js

exportdefault{  plugins:[newSvgChunkWebpackPlugin({      filename:'[name].svg'})]};

[!NOTE]Thefilename parameter is compatible with Webpack caching placeholders, see the sectioncaching.

svgstoreConfig

Type:

typesvgstoreConfig= object;

Default:{ cleanDefs: false, cleanSymbols: false, inline: true }

SVG sprites are built using thesvgstore package. Update the parameters according to your needs from the options list available on thesvgstore documentation.

webpack.config.js

exportdefault{  plugins:[newSvgChunkWebpackPlugin({      svgstoreConfig:{        svgAttrs:{'aria-hidden':true,          style:'position: absolute; width: 0; height: 0; overflow: hidden;'}}})]};

[!NOTE]To avoid LinearGradient conflicts, avoid thedisplay: none property which breaks SVG definitions.

generateSpritesManifest

Type:

typegenerateSpritesManifest=boolean;

Default:false

Tells the plugin whether to generate thesprites-manifest.json. The JSON file contains the list of all SVG included by entrypoints.

webpack.config.js

exportdefault{  plugins:[newSvgChunkWebpackPlugin({      generateSpritesManifest:true})]};

generateSpritesPreview

Type:

typegenerateSpritesPreview=boolean;

Default:false

Tells the plugin whether to generate thesprites-preview.html. The HTML preview contains a display list of all SVG included by entrypoints with the SVG overviews and the names. See thesprites preview of the example.

webpack.config.js

exportdefault{  plugins:[newSvgChunkWebpackPlugin({      generateSpritesPreview:true})]};

Caching

Withwebpack caching, several placeholders are available depending on your needs. With SVG inlined in the page, this option is not useful.

[!NOTE]The[contenthash] placeholder is the best option because it depends on the sprite content. Cache placeholders are expensive in build performance, use it only in production mode.

[contenthash]

The[contenthash] placeholder will add a unique hash based on the content of the sprite. When the sprite's content changes, the hash will change as well.

webpack.config.js

exportdefault{  plugins:[newSvgChunkWebpackPlugin({      filename:'[name].[contenthash].svg'})]};

[fullhash]

The[fullhash] placeholder will add a unique hash generated for every build. When the compilation build is updated, the hash will change as well.

webpack.config.js

exportdefault{  plugins:[newSvgChunkWebpackPlugin({      filename:'[name].[fullhash].svg'})]};

License

svg-chunk-webpack-plugin is licensed under theMIT License.

Created with ♥ by@yoriiis.

2 Contributors

yoriiisalexander-akait

[8]ページ先頭

©2009-2025 Movatter.jp