Package detail

svg-sprite-loader

JetBrains866.8kMIT6.0.11

Webpack loader for creating SVG sprites

svg, sprite, svg sprite, svg stack

readme

SVG sprite loader

NPM version Build status Documentation score Dependencies status Dev dependencies status NPM downloads

Webpack loader for creating SVG sprites.

:tada: 2.0 is out, please read the migration guide & overview.

:warning: For old v0.x versions see the README in the v0 branch.

Table of contents

Why it's cool

  • Minimum initial configuration. Most of the options are configured automatically.
  • Runtime for browser. Sprites are rendered and injected in pages automatically, you just refer to images via <svg><use xlink:href="#id"></use></svg>.
  • Isomorphic runtime for node/browser. Can render sprites on server or in browser manually.
  • Customizable. Write/extend runtime module to implement custom sprite behaviour. Write/extend runtime generator to produce your own runtime, e.g. React component configured with imported symbol.
  • External sprite file is generated for images imported from css/scss/sass/less/styl/html (SVG stacking technique).

Installation

npm install svg-sprite-loader -D
# via yarn
yarn add svg-sprite-loader -D

Configuration

// webpack 1
{
  test: /\.svg$/,
  loader: 'svg-sprite-loader',
  query: { ... }
}

// webpack 1 multiple loaders
{
  test: /\.svg$/,
  loaders: [
    `svg-sprite-loader?${JSON.stringify({ ... })}`,
    'svg-transform-loader',
    'svgo-loader'
  ]
}

// webpack >= 2
{
  test: /\.svg$/,
  loader: 'svg-sprite-loader',
  options: { ... }
}

// webpack >= 2 multiple loaders
{
  test: /\.svg$/,
  use: [
    { loader: 'svg-sprite-loader', options: { ... } },
    'svg-transform-loader',
    'svgo-loader'
  ]
}

symbolId (string | function(path, query), default [name])

How <symbol> id attribute should be named. All patterns from loader-utils#interpolateName are supported. Also can be a function which accepts 2 args - file path and query string and return symbol id:

{
  symbolId: filePath => path.basename(filePath)
}

symbolRegExp (default '')

Passed to the symbolId interpolator to support the [N] pattern in the loader-utils name interpolator

esModule (default true, autoconfigured)

Generated export format:

  • when true loader will produce export default ....
  • when false the result is module.exports = ....

By default depends on used webpack version: true for webpack >= 2, false otherwise.

Runtime configuration

When you require an image, loader transforms it to SVG <symbol>, adds it to the special sprite storage and returns class instance that represents symbol. It contains id, viewBox and content (id, viewBox and url in extract mode) fields and can later be used for referencing the sprite image, e.g:

import twitterLogo from './logos/twitter.svg';
// twitterLogo === SpriteSymbol<id: string, viewBox: string, content: string>
// Extract mode: SpriteSymbol<id: string, viewBox: string, url: string, toString: Function>

const rendered = `
<svg viewBox="${twitterLogo.viewBox}">
  <use xlink:href="#${twitterLogo.id}" />
</svg>`;

When browser event DOMContentLoaded is fired, sprite will be automatically rendered and injected in the document.body. If custom behaviour is needed (e.g. a different mounting target) default sprite module could be overridden via spriteModule option. Check example below.

spriteModule (autoconfigured)

Path to sprite module that will be compiled and executed at runtime. By default it depends on target webpack config option:

  • svg-sprite-loader/runtime/browser-sprite.build for 'web' target.
  • svg-sprite-loader/runtime/sprite.build for other targets.

If you need custom behavior, use this option to specify a path of your sprite implementation module. Path will be resolved relative to the current webpack build folder, e.g. utils/sprite.js placed in current project dir should be written as ./utils/sprite.

Example of sprite with custom mounting target (copypasted from browser-sprite):

import BrowserSprite from 'svg-baker-runtime/src/browser-sprite';
import domready from 'domready';

const sprite = new BrowserSprite();
domready(() => sprite.mount('#my-custom-mounting-target'));

export default sprite; // don't forget to export!

It's highly recommended to extend default sprite classes:

symbolModule (autoconfigured)

Same as spriteModule, but for sprite symbol. By default also depends on target webpack config option:

  • svg-baker-runtime/browser-symbol for 'web' target.
  • svg-baker-runtime/symbol for other targets.

runtimeGenerator (default generator)

Path to node.js script that generates client runtime. Use this option if you need to produce your own runtime, e.g. React component configured with imported symbol. Example.

runtimeCompat (default false, deprecated)

Should runtime be compatible with earlier v0.x loader versions. This option will be removed in the next major version release.

runtimeOptions

Arbitrary data passed to runtime generator. Reserved for future use when other runtime generators will be created.

Extract configuration

In the extract mode loader should be configured with plugin, otherwise an error is thrown. Example:

// webpack.config.js
const SpriteLoaderPlugin = require('svg-sprite-loader/plugin');

...

{
  plugins: [
    new SpriteLoaderPlugin()
  ]
}

extract (default false, autoconfigured)

Switches loader to the extract mode. Enabled automatically for images imported from css/scss/sass/less/styl/html files.

spriteFilename (type string|Function<string>,default sprite.svg)

Filename of extracted sprite. Multiple sprites can be generated by specifying different loader rules restricted with include option or by providing custom function which recieves SVG file absolute path, e.g.:

{
  test: /\.svg$/,
  loader: 'svg-sprite-loader',
  options: {
    extract: true,
    spriteFilename: svgPath => `sprite${svgPath.substr(-4)}`
  }
}

[hash] in sprite filename will be replaced by it's content hash. It is also possible to generate sprite for each chunk by using [chunkname] pattern in spriteFilename option. This is experimental feature, use it with caution!

publicPath (type: string, default: __webpack_public_path__)

Custom public path for sprite file.

{
  test: /\.svg$/,
  loader: 'svg-sprite-loader',
  options: {
    extract: true,
    publicPath: '/'
  }
}

outputPath (type: string, default: null`)

Custom output path for sprite file. By default it will use publicPath. This param is useful if you want to store sprite is a directory with a custom http access.

{
  test: /\.svg$/,
  loader: 'svg-sprite-loader',
  options: {
    extract: true,
    outputPath: 'custom-dir/sprites/'
    publicPath: 'sprites/'
  }
}

Plain sprite

You can render plain sprite in extract mode without styles and usages. Pass plainSprite: true option to plugin constructor:

{
  plugins: [
    new SpriteLoaderPlugin({ plainSprite: true })
  ]
}

Sprite attributes

Sprite <svg> tag attributes can be specified via spriteAttrs plugin option:

{
  plugins: [
    new SpriteLoaderPlugin({
      plainSprite: true,
      spriteAttrs: {
        id: 'my-custom-sprite-id'
      }
    })
  ]
}

Examples

See examples folder.

Contributing guidelines

See CONTRIBUTING.md.

License

See LICENSE

Credits

Huge thanks for all this people.

changelog

Change Log

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

6.0.11 (2021-10-24)

6.0.10 (2021-10-18)

6.0.9 (2021-06-23)

Bug Fixes

  • utils: force get-matched-rule-4 to use nearest webpack installation (#463) (dcaa65a)

6.0.8 (2021-06-21)

Bug Fixes

  • utils: fix: some options had no effect with webpack5 (#460) (839f878), closes #446

6.0.7 (2021-05-28)

Bug Fixes

6.0.6 (2021-04-23)

Bug Fixes

  • utils: use webpack object version if package can't be required (f4b82c2)

6.0.5 (2021-04-10)

Bug Fixes

  • utils: use moduleGraph in is-module-should-be-extracted.js (6099812)

6.0.4 (2021-04-10)

Bug Fixes

  • utils: NormalModule for webpack 5 (00886bc)

6.0.3 (2021-04-10)

Bug Fixes

  • utils: fix 'Properties descriptionData are unknown' with webpack5 (5a4fc6a)
  • utils: use moduleGraph and chunkGraph if possible (9e25d18)

6.0.2 (2021-03-18)

6.0.1 (2021-03-18)

6.0.0 (2021-03-13)

Bug Fixes

  • additional-assets: adds missing method (8db9c4d)
  • loader: get rid of webpack--version (54a0c6b), closes #437 #417

BREAKING CHANGES

  • loader: delete get-webpack-version.js

5.2.1 (2020-12-14)

5.2.0 (2020-12-14)

Features

5.1.1 (2020-12-05)

5.1.0 (2020-12-05)

Features

5.0.0 (2020-05-11)

Bug Fixes

  • pass proper context param to runtime generator (c084ec7), closes #186

BREAKING CHANGES

  • Possible breaks third-party runtime generators. Earlier context param was containing path to compilation root context, e.g. folder where webpack compilation occurs. This is wrong behaviour, because meaning of this param is a folder where svg image is located. So it was changed in this commit. If your custom runtime generator breaks after this update use loaderContext.rootContext option instead of context.

4.3.0 (2020-05-03)

Features

  • outputPath: add possibility to define output path (2c7eceb)

4.2.7 (2020-04-28)

Bug Fixes

  • move mask & clipPath elements outside symbol (ae70786), closes #325

4.2.6 (2020-04-26)

Bug Fixes

  • drop webpack version detector (7131578)

4.2.5 (2020-04-12)

Bug Fixes

  • refers to transpiled code in svg-baker-runtime (65ece05), closes #385

4.2.4 (2020-04-12)

Bug Fixes

  • don't create additional chunk for sprite (80ebfa3), closes #364

4.2.3 (2020-04-08)

Bug Fixes

  • check properly when window.angular properly (1c76824)

4.2.2 (2020-04-02)

Bug Fixes

  • add aria-hidden attribute to sprite node for proper accessibility behaviour (bb08665), closes #315

4.2.1 (2020-01-31)

Bug Fixes

  • drop npm-shrinkwrap.json due to it causes installation of old dependencies when npm is used (7439e61), closes #378 #379

4.2.0 (2020-01-24)

Bug Fixes

Features

  • add clipPath & mask to "move-from-symbol-to-root" transform defaults (02d0c33), closes #288 #325

4.1.6 (2019-04-27)

Bug Fixes

  • incorrect items order after sorting (ded8146)

4.1.5 (2019-04-27)

Bug Fixes

  • replace all instances of urls in attribute (d6fdf94), closes #300

4.1.4 (2019-04-27)

Bug Fixes

  • incorrect detection webpack version, closes #309
  • Fix the bug of publicPath, closes #311
  • configuration make possible to use oneOf in loader rules
  • configuration: make default config work with yarn PnP (dc931e2)
  • runtime-generator: fix module not found errors for custom spriteModule or symbolModule (44bbcfe)

4.1.3 (2018-10-29)

Bug Fixes

  • update svg-baker to fix security vulnerability (4408ccd)

4.1.2 (2018-09-28)

Bug Fixes

  • drop webpack dependency (6254f9c)

4.1.1 (2018-09-19)

Bug Fixes

  • interpolate publicPath properly (22f10e6)

4.1.0 (2018-09-19)

Features

  • add ARIA attrs to whitelist symbol attributes (4bbccab), closes #304

4.0.0 (2018-09-19)

3.9.0 (2018-05-26)

Features

  • support symbol id interpolator as function (3691d86)

3.8.0 (2018-05-26)

Bug Fixes

  • error link in pr template (7b6cf30)

Features

  • support publicPath option (793a7bf)
  • support custom outputPath (80f7520)

3.7.3 (2018-03-19)

Bug Fixes

  • utils: fix linting errors (f5239a0)
  • utils: prevent errors for modules without resources (467daa6)

3.7.2 (2018-03-19)

3.7.1 (2018-03-12)

Bug Fixes

  • loader: wrong build target (66e98f9)

3.7.0 (2018-03-10)

Features

3.6.2 (2017-12-27)

Bug Fixes

  • plugin: prevent outer symbol ast modifications (0c8c3d0)

3.6.1 (2017-12-25)

Bug Fixes

  • plugin: don't hide sprite by default (fd629bd)

3.6.0 (2017-12-22)

Features

  • plugin: add ability to specify sprite attributes in extract mode (a6a5e30)

3.5.4 (2017-12-19)

Bug Fixes

  • plugin: refer to sprite file properly in plainSprite mode (e4789a4)

3.5.3 (2017-12-19)

Bug Fixes

  • loader: drop "2 applied rules" warning (e18f7d6)

3.5.2 (2017-12-12)

Bug Fixes

  • loader: #203 support use in rule.oneOf (cb3d2da)

3.5.1 (2017-12-08)

Bug Fixes

  • package: drop postinstall script (8a46c78)

3.5.0 (2017-12-08)

Features

  • loader: add functional type of spriteFilename (297a957)

3.4.1 (2017-10-23)

Bug Fixes

  • plugin: make sprite file hash more stable (7e9c53e)

3.4.0 (2017-10-19)

Features

  • better html-webpack-plugin interop in extract mode (8a2d63e)

3.3.1 (2017-10-16)

Bug Fixes

  • loader: check this.cacheable existence before call it (c1ed50a)

3.3.0 (2017-10-16)

Features

  • plugin: allow to render external sprite without styles and usages (fcf3939)

3.2.6 (2017-09-28)

Bug Fixes

  • loader: #187 support rule.oneOf config (75df92e)
  • loader: support resourceQuery in extract mode with webpack version above 1 (6652d78)

3.2.5 (2017-08-31)

Bug Fixes

  • runtime: don't encode "(", ")" and "~" symbols when replacing urls in <use> references (388ce74)

3.2.4 (2017-08-20)

Bug Fixes

  • preserve `fill` and `stroke` attrs when transform svg to symbol (d845aa3)

3.2.3 (2017-08-18)

Bug Fixes

  • deal with deprecation warnings from webpack 3 (d150035)

3.2.2 (2017-08-17)

Bug Fixes

  • plugin: webpack-manifest-plugin compatibility (d88ac31)

3.2.1 (2017-08-16)

Bug Fixes

  • runtime: apply styles in dynamically appended symbols in Edge (299bfe2)

3.2.0 (2017-08-16)

Features

  • runtime: add ability to create sprite from existing DOM node (4056d7b)

3.1.7 (2017-08-15)

Bug Fixes

  • runtime: store global sprite object in window which allows to mount symbols in one place betwee (13e3d47)

3.1.6 (2017-08-10)

Bug Fixes

  • loader: interpolate sprite filename properly (b17e5e0)

3.1.5 (2017-08-10)

Bug Fixes

  • loader: throw an exception if input is not valid SVG (413246e), closes #170

3.1.4 (2017-08-09)

Bug Fixes

  • loader: quick workaround for breaking changes in webpack@3.5 (modules prop dropped in ConcatenatedModule) (f15030d)

3.1.3 (2017-08-08)

Bug Fixes

  • loader: throw proper error message when runtime not found (ef83fac)

3.1.2 (2017-08-05)

Bug Fixes

  • loader: decode entities in <style> tags (36e6ba6)

3.1.1 (2017-08-04)

Bug Fixes

  • loader: handle case when rule test is a function (ace9f47)

3.1.0 (2017-08-03)

Features

  • loader: webpack 3 module concatenation interop in extract mode (8a79536)

3.0.11 (2017-08-03)

Bug Fixes

  • runtime: pass proper old URL in Angular workaround (fbda8a2)

3.0.10 (2017-07-31)

Configuration

  • configuration: add support for symbolRegExp pattern in symbol name interpolation (e9de712)

3.0.9 (2017-07-31)

Bug Fixes

  • runtime: fix IE/Edge rendering with SVG containing 'style' elements (dcc9e27)

3.0.8 (2017-07-28)

Bug Fixes

  • runtime: fallback to early sprite mount when document.body appears (a71e67a)

3.0.7 (2017-07-24)

Bug Fixes

  • runtime-generator: return symbol id string in compat mode (7641af0)

3.0.6 (2017-07-17)

Bug Fixes

  • loader: add support for issuer when matching rules (5d21b2f)

3.0.5 (2017-06-02)

Bug Fixes

  • loader: replace sprite filename in whole source (d4d4429)

3.0.4 (2017-05-31)

Bug Fixes

  • utils: properly replace path to image with sprite name on Windows (6bdd6cd)

3.0.3 (2017-05-29)

Bug Fixes

  • configuration: proper configurator runtime selection based on `target` loader context (a7365a2)

3.0.2 (2017-05-24)

Bug Fixes

  • loader: check module request properly in isModuleShouldBeExtracted with DLL Plugin (ffb7b04)

3.0.1 (2017-05-22)

Bug Fixes

  • runtime-generator: runtime generator in extract mode return object instead of string (208b6dc)

3.0.0 (2017-05-21)

Features

  • loader: runtime exports an object in extract mode (f0af0eb)

Reverts

  • tools: rollback to standart-version :) (b948e65)

BREAKING CHANGES

  • loader: Generated runtime in extract mode is changed from string to object

ISSUES CLOSED: #123

2.1.0 (2017-05-13)

Bug Fixes

  • multiple: update svg-baker deps (ead7d68), closes #101 #103 #112
  • runtime: update svg-baker-runtime with fixed angular workaround (1543029), closes #103

Features

2.0.6 (2017-05-13)

Bug Fixes

  • configure: use browser-sprite``browser-symbol for electron-renderer target (b9a3ed0)

2.1.0-3 [beta] (2017-05-10)

Bug Fixes

  • plugin: properly replace paths on Windows (0c70caa), closes #106

2.1.0-2 [beta] (2017-05-09)

Bug Fixes

  • loader: symbol id interpolation (18edd99)

2.1.0-1 [beta] (2017-05-08)

Bug Fixes

  • plugin: properly generate symbol url in extract mode (6af7230)

2.1.0-0 [beta] (2017-05-07)

Bug Fixes

  • utils: fix default import (0c34daa)

Features

  • interop: extract-text-webpack-plugin & html-webpack-plugin interop (a38fdcc)
  • interop: extract-text-webpack-plugin with allChunks: true interoperability (63d347d)
  • spritehash: add ability to use [spritehash] substitution token in spriteFilename (f9eba1b)

2.0.5 (2017-05-05)