Webpack SVG sprite loader for boi
声明:此loader是在svg-sprite-loader为基础,针对本人具体的项目需求做了些微修改。
以下是原文档:
It's like style-loader but for SVG:
- Creates a single SVG sprite from a set of images.
- Raster images support (PNG, JPG and GIF).
- Custom sprite implementation support.
How it works
When you require an image, loader transforms it to SVG symbol and add it to the array in special sprite class.
When browser event DOMContentLoaded
fires sprite will be rendered and injected as first child of document.body
.
Require statement e.g. require('svg-sprite!./image.svg')
returns a symbol id, so you can reference it later
in <svg><use xlink:href="#id"/></svg>
. Raster images will be inlined (base64) and wrapped with an <image>
tag.
Files like image@2x.png
will be transformed with proper scale.
Custom sprite implementation
By default sprite renders when DOMContentLoaded
event fires and injects as first child in document.body
.
If you need custom behavior, use spriteModule
config option to specify module path of your sprite implementation.
You can extend a default lib/web/sprite.js
, or create your own.
In the latter case you only need to implement the add
method that accepts the symbol data as a string.
Installation
npm install svg-sprite-loader --save-dev
Example config
moduleexports = module: loaders: test: /\.svg$/ loader: 'svg-sprite?' + JSON ;
Configuration
name
configures a custom symbol id naming. Default is[name]
. Following name patterns are supported:[ext]
the extension of the image.[name]
the basename of the image.[path]
the path of the image.[hash]
the hash or the image content.[pathhash]
the hash or the image path.
angularBaseWorkaround
Adds workaround for issue with combination of<base>
and History API which is typical for Angular.js. Default isfalse
.prefixize
isolates an image content by prefixing itsid
,xlink:href
andurl(#id)
elements. Default istrue
.spriteModule
defines custom sprite implementation module path.
Examples
Single image
var id = ;// => 'image'
Set of images
var files = require;files;
Custom sprite behavior
// my-sprite.jsvar Sprite = ;moduleexports = ; // my-app.jsxvar sprite = ; Component { spriteelem = sprite; } { spriteelemparentNode; }
Using with React
// icon.jsxvar GLYPHS = PONY: UNICORN: ; Component { var glyph = thispropsglyph; return <svg className="icon" dangerouslySetInnerHTML=__html: '<use xlink:href="' + glyph + '"></use>'/> } moduleexports = Icon;moduleexportsGLYPHS = GLYPHS; // some-component.jsxvar Icon = ;<Icon glyph=IconGLYPHSUNICORN>
Usage with React 0.14
// icon.jsx{ return <svg className=className width=width height=height> <use xlinkHref=glyph /> </svg> ;} // some-component.jsx;; <Icon glyph=help />