- Saved searches
- Use saved searches to filter your results more quickly
- License
- JetBrains/svg-sprite-loader
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- How to auto-generate SVG sprites with webpack and svg-sprite-loader
- What is an SVG sprite?
- Installation and setup
- Styling the icons
- Advanced setup
- Icon component
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Webpack loader for creating SVG sprites.
License
JetBrains/svg-sprite-loader
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Webpack loader for creating SVG sprites.
- Why it’s cool
- Installation
- Configuration
- symbolId
- symbolRegExp
- esModule
- Runtime configuration
- spriteModule
- symbolModule
- runtimeGenerator
- runtimeCompat (deprecated)
- runtimeOptions
- extract
- spriteFilename
- publicPath
- outputPath
- plainSprite
- spriteAttrs
- 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 .
- 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).
npm install svg-sprite-loader -D # via yarn yarn add svg-sprite-loader -D
// 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 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) >
Passed to the symbolId interpolator to support the [N] pattern in the loader-utils name interpolator
esModule (default true , autoconfigured)
- 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.
When you require an image, loader transforms it to SVG , 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 // Extract mode: SpriteSymbol const rendered = ` $twitterLogo.viewBox>"> $twitterLogo.id>" /> `;
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.
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:
Same as spriteModule , but for sprite symbol. By default also depends on target webpack config option:
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.
Arbitrary data passed to runtime generator. Reserved for future use when other runtime generators will be created.
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 ,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/' > >
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 tag attributes can be specified via spriteAttrs plugin option:
plugins: [ new SpriteLoaderPlugin( plainSprite: true, spriteAttrs: id: 'my-custom-sprite-id' > >) ] >
How to auto-generate SVG sprites with webpack and svg-sprite-loader
When developing, there are several benefits to using SVG sprites, but maintaining sprites can quickly become difficult and time-consuming. With Webpack and svg-sprite-loader your sprite will be automatically generated when you bundle your code.
What is an SVG sprite?
A sprite is a collection of something, ex. images, put into a single file. This can be an advantage because a web page with many images may generate multiple server requests and can take a long time to load. Using image sprites will reduce the number of server requests and save bandwidth.
An SVG sprite is a file that contains several symbols/icons that can be used independently. Using a sprite like this gives some benefits for frontend development:
- it is simple to use,
- icons are reusable,
- it is possible to style the same icon with different colors in different places. Thus, you do not need separate SVG’s with icons in different colors.
Installation and setup
A basic setup is fairly simple. Install svg-sprite-loader with npm or yarn
# NPM npm install svg-sprite-loader -D # yarn yarn add svg-sprite-loader -D
and create a separate rule for SVG’s in your webpack config
This will create a sprite within your bundled *.js file. The svg-sprite-loader transforms each imported SVG to a symbol within the sprite that has a unique id. By default this id is the same as the SVG filename.
Now you can import all the SVG’s you need into your code and use them within an SVG tag with the SVG’s id:
// *.js import "/path/to/icons/logo.svg";
Styling the icons
The color of the icons can be set to the same color as the font with the styling fill: currentColor . This will also make it possible to change the SVG color with the styling color instead of fill .
Advanced setup
I will not go into detail about the config for different setups, but other options are:
- creating multiple sprites by adding rules for different folders
- extract the sprite as a separate file from the bundle and set a different output path
- change the name of the sprite file with the spriteFilename option
- change the name of icons with the symbolId option
Icon component
The generated sprite will only contain the SVG’s that you import into your code. That means that if you forget to import a file you will not get an icon within the sprite and the svg will display an empty box.
If you are using a framework like Vue.js or React.js you might want to create an Icon component that imports all the icons you need. That way you know that all your svg’s are in the sprite at all times, but that also means that you should tidy up your icons folder, so you don’t import a lot of unused icons.
I use Vue.js and my Icon component looks something like this:
.icon
In our app or other components we can now import and use our Icon component like this:
. .