Code Monkey home page Code Monkey logo

yoriiis / svg-chunk-webpack-plugin Goto Github PK

View Code? Open in Web Editor NEW
19.0 3.0 1.0 1.1 MB

Generate SVG sprites according to entrypoint dependencies. Each page only imports its own svgs, wrapped as a sprite and optimized by SVGO

Home Page: https://webpack.js.org/plugins/svg-chunk-webpack-plugin

License: MIT License

JavaScript 66.84% TypeScript 33.16%
svg svg-sprite svgo svgstore webpack webpack-plugin webpack-loader chunk optimization minification

svg-chunk-webpack-plugin's Introduction

SvgChunkWebpackPlugin

GitHub Workflow Status (branch) Coverage Status

The svg-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 popular SVGO 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 section using configuration.

Installation

The plugin is available as a package with the name of svg-chunk-webpack-plugin on npm and Github.

npm install svg-chunk-webpack-plugin --save-dev
yarn add svg-chunk-webpack-plugin --dev

Warning svg-chunk-webpack-plugin@5 is ESM only.

Note Minimum supported Node.js version is 16.20.0 and Webpack >=5.10.3.

Example

The project includes a minimalist example in the ./example directory. Run the npm 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 be home.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 SvgChunkWebpackPlugin from 'svg-chunk-webpack-plugin';

export default {
  module: {
    rules: [
      {
        test: /\.svg$/,
        use: [
          {
            loader: SvgChunkWebpackPlugin.loader
          }
        ]
      }
    ]
  },
  plugins: [new SvgChunkWebpackPlugin()]
};

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>
  <use href="#<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:

type configFile = string | boolean;

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

Tells the loader whether to load the custom SVGO configuration. Custom configuration can be disabled with configFile: false.

webpack.config.js

export default {
  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. See how to configure svgo for details.

svgo.config.js

export default {
  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:

type filename = 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

export default {
  plugins: [
    new SvgChunkWebpackPlugin({
      filename: '[name].svg'
    })
  ]
};

Note The filename parameter is compatible with Webpack caching placeholders, see the section caching.

svgstoreConfig

Type:

type svgstoreConfig = object;

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

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

webpack.config.js

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

Note To avoid LinearGradient conflicts, avoid the display: none property which breaks SVG definitions.

generateSpritesManifest

Type:

type generateSpritesManifest = boolean;

Default: false

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

webpack.config.js

export default {
  plugins: [
    new SvgChunkWebpackPlugin({
      generateSpritesManifest: true
    })
  ]
};

generateSpritesPreview

Type:

type generateSpritesPreview = boolean;

Default: false

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

webpack.config.js

export default {
  plugins: [
    new SvgChunkWebpackPlugin({
      generateSpritesPreview: true
    })
  ]
};

Caching

With webpack 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

export default {
  plugins: [
    new SvgChunkWebpackPlugin({
      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

export default {
  plugins: [
    new SvgChunkWebpackPlugin({
      filename: '[name].[fullhash].svg'
    })
  ]
};

License

svg-chunk-webpack-plugin is licensed under the MIT License.

Created with โ™ฅ by @yoriiis.

svg-chunk-webpack-plugin's People

Contributors

alexander-akait avatar dependabot[bot] avatar yoriiis avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

svg-chunk-webpack-plugin's Issues

Upgrade SVGO package to v2.x.x

Describe the bug

npm WARN deprecated [email protected]: This SVGO version is no longer supported. Upgrade to v2.x.x.

Steps to reproduce

To reproduce the problem, simply install the package.

Expected behavior

No deprecation warning =)

Screenshots and recordings

No response

SvgChunkWebpackPlugin

2.0.1

webpack

5.54.0

Node.js & npm

node: 16.14.2 & npm: 8.5.0

OS

macOS 12.1

Additional context

No response

Support rspack

If the feature solves a problem you have, specify it here.

I'm trying to migrate our webpack project to rspack, everything is working except the svg-sprites, as this project is in active development, I hope you will consider support for rspack as well.

Describe the proposed feature.

Getting error -
/node_modules/svg-chunk-webpack-plugin/lib/loader.js:20
this._module.factoryMeta = this._module.factoryMeta || {};
^

TypeError: Cannot read properties of undefined (reading 'factoryMeta')
at Object.SvgChunkWebpackLoader

Describe alternatives you've considered

svg-sprite-loader

Additional context

Minimal example repo - https://github.com/singh-jay/svg-chunk-plugin-test

Importance

Nice to have

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.