UNPKG

10.3 kBMarkdownView Raw
1# SVG sprite loader
2[![NPM version][version-img]][versions-img] [![Build status][ci-img]][ci-url] [![Documentation score][docs-coverage-img]][docs-coverage-url] [![Dependencies status][deps-img]][deps-url] [![Dev dependencies status][dev-deps-img]][dev-deps-url] [![NPM downloads][downloads-img]][npm-url]
3
4Webpack loader for creating SVG sprites.
5
6> :tada: 2.0 is out, please read the [migration guide & overview](2.0.md).
7
8> :warning: For old v0.x versions see [the README in the v0 branch](https://github.com/JetBrains/svg-sprite-loader/blob/v0/README.md).
9
10## Table of contents
11
12- [Why it's cool](#why-its-cool)
13- [Installation](#installation)
14- [Live support](#live-support)
15- [Configuration](#configuration)
16 - [`symbolId`](#symbol-id)
17 - [`symbolRegExp`](#symbol-regexp)
18 - [`esModule`](#es-module)
19 - [Runtime configuration](#runtime-configuration)
20 - [`spriteModule`](#sprite-module)
21 - [`symbolModule`](#symbol-module)
22 - [`runtimeGenerator`](#runtime-generator)
23 - [`runtimeCompat`](#runtime-compat) (deprecated)
24 - [`runtimeOptions`](#runtime-options)
25 - [Extract configuration](#extract-configuration)
26 - [`extract`](#extract)
27 - [`spriteFilename`](#sprite-filename)
28 - [`publicPath`](#public-path)
29 - [`plainSprite`](#plain-sprite)
30 - [`spriteAttrs`](#sprite-attrs)
31- [Examples](#examples)
32- [Contributing guidelines](#contributing-guidelines)
33- [License](#license)
34- [Credits](#credits)
35
36## Why it's cool
37
38- **Minimum initial configuration**. Most of the options are configured automatically.
39- **Runtime for browser**. Sprites are rendered and injected in pages automatically, you just refer to images via `<svg><use xlink:href="#id"></use></svg>`.
40- **Isomorphic runtime for node/browser**. Can render sprites on server or in browser manually.
41- **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.
42- **External sprite file** is generated for images imported from css/scss/sass/less/styl/html ([SVG stacking technique](https://css-tricks.com/svg-fragment-identifiers-work/#article-header-id-4)).
43
44## Installation
45
46```bash
47npm install svg-sprite-loader -D
48# via yarn
49yarn add svg-sprite-loader -D
50```
51
52## Configuration
53
54```js
55// webpack 1
56{
57 test: /\.svg$/,
58 loader: 'svg-sprite-loader',
59 query: { ... }
60}
61
62// webpack 1 multiple loaders
63{
64 test: /\.svg$/,
65 loaders: [
66 `svg-sprite-loader?${JSON.stringify({ ... })}`,
67 'svg-transform-loader',
68 'svgo-loader'
69 ]
70}
71
72// webpack >= 2
73{
74 test: /\.svg$/,
75 loader: 'svg-sprite-loader',
76 options: { ... }
77}
78
79// webpack >= 2 multiple loaders
80{
81 test: /\.svg$/,
82 use: [
83 { loader: 'svg-sprite-loader', options: { ... } },
84 'svg-transform-loader',
85 'svgo-loader'
86 ]
87}
88```
89
90<a id="symbol-id"></a>
91### `symbolId` (`string | function(path, query)`, default `[name]`)
92
93How `<symbol>` `id` attribute should be named. All patterns from [loader-utils#interpolateName](https://github.com/webpack/loader-utils#interpolatename)
94are supported. Also can be a function which accepts 2 args - file path and query string and return symbol id:
95
96```js
97{
98 symbolId: filePath => path.basename(filePath)
99}
100```
101
102<a id="symbol-regexp"></a>
103### `symbolRegExp` (default `''`)
104Passed to the symbolId interpolator to support the [N] pattern in the loader-utils name interpolator
105
106<a id="es-module"></a>
107### `esModule` (default `true`, autoconfigured)
108
109Generated export format:
110- when `true` loader will produce `export default ...`.
111- when `false` the result is `module.exports = ...`.
112
113By default depends on used webpack version: `true` for webpack >= 2, `false` otherwise.
114
115## Runtime configuration
116
117When you require an image, loader transforms it to SVG `<symbol>`, adds it to the special sprite storage and returns class instance
118that represents symbol. It contains `id`, `viewBox` and `content` (`id`, `viewBox` and `url` in extract mode)
119fields and can later be used for referencing the sprite image, e.g:
120
121```js
122import twitterLogo from './logos/twitter.svg';
123// twitterLogo === SpriteSymbol<id: string, viewBox: string, content: string>
124// Extract mode: SpriteSymbol<id: string, viewBox: string, url: string, toString: Function>
125
126const rendered = `
127<svg viewBox="${twitterLogo.viewBox}">
128 <use xlink:href="#${twitterLogo.id}" />
129</svg>`;
130```
131
132When browser event `DOMContentLoaded` is fired, sprite will be automatically rendered and injected in the `document.body`.
133If custom behaviour is needed (e.g. a different mounting target) default sprite module could be overridden via `spriteModule` option. Check example below.
134
135<a id="sprite-module"></a>
136### `spriteModule` (autoconfigured)
137
138Path to sprite module that will be compiled and executed at runtime.
139By default it depends on [`target`](https://webpack.js.org/configuration/target) webpack config option:
140- `svg-sprite-loader/runtime/browser-sprite.build` for 'web' target.
141- `svg-sprite-loader/runtime/sprite.build` for other targets.
142
143If you need custom behavior, use this option to specify a path of your sprite implementation module.
144Path 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`.
145
146Example of sprite with custom mounting target (copypasted from [browser-sprite](https://github.com/JetBrains/svg-sprite-loader/blob/master/runtime/browser-sprite.js)):
147
148```js
149import BrowserSprite from 'svg-baker-runtime/src/browser-sprite';
150import domready from 'domready';
151
152const sprite = new BrowserSprite();
153domready(() => sprite.mount('#my-custom-mounting-target'));
154
155export default sprite; // don't forget to export!
156```
157
158It's highly recommended to extend default sprite classes:
159- [for browser-specific env](https://github.com/JetBrains/svg-baker/blob/master/packages/svg-baker-runtime/src/browser-sprite.js)
160- [for isomorphic env](https://github.com/JetBrains/svg-baker/blob/master/packages/svg-baker-runtime/src/sprite.js)
161
162<a id="symbol-module"></a>
163### `symbolModule` (autoconfigured)
164
165Same as `spriteModule`, but for sprite symbol. By default also depends on `target` webpack config option:
166- `svg-baker-runtime/browser-symbol` for 'web' target.
167- `svg-baker-runtime/symbol` for other targets.
168
169<a id="runtime-generator"></a>
170### `runtimeGenerator` ([default generator](https://github.com/JetBrains/svg-sprite-loader/blob/master/lib/runtime-generator.js))
171
172Path to node.js script that generates client runtime.
173Use this option if you need to produce your own runtime, e.g. React component configured with imported symbol. [Example](https://github.com/JetBrains/svg-sprite-loader/tree/master/examples/custom-runtime-generator).
174
175<a id="runtime-compat"></a>
176### `runtimeCompat` (default `false`, deprecated)
177
178Should runtime be compatible with earlier v0.x loader versions. This option will be removed in the next major version release.
179
180<a id="runtime-options"></a>
181### `runtimeOptions`
182
183Arbitrary data passed to runtime generator. Reserved for future use when other runtime generators will be created.
184
185## Extract configuration
186
187In the extract mode loader should be configured with plugin, otherwise an error is thrown. Example:
188
189```js
190// webpack.config.js
191const SpriteLoaderPlugin = require('svg-sprite-loader/plugin');
192
193...
194
195{
196 plugins: [
197 new SpriteLoaderPlugin()
198 ]
199}
200```
201
202<a id="extract"></a>
203### `extract` (default `false`, autoconfigured)
204
205Switches loader to the extract mode.
206Enabled automatically for images imported from css/scss/sass/less/styl/html files.
207
208<a id="sprite-filename"></a>
209### `spriteFilename` (type `string|Function<string>`,default `sprite.svg`)
210
211Filename of extracted sprite. Multiple sprites can be generated by specifying different loader rules restricted with `include` option or
212by providing custom function which recieves SVG file absolute path, e.g.:
213
214```js
215{
216 test: /\.svg$/,
217 loader: 'svg-sprite-loader',
218 options: {
219 extract: true,
220 spriteFilename: svgPath => `sprite${svgPath.substr(-4)}`
221 }
222}
223```
224
225`[hash]` in sprite filename will be replaced by it's content hash.
226It is also possible to generate sprite for each chunk by using `[chunkname]` pattern in spriteFilename option. This is experimental feature, use it with caution!
227
228<a id="public-path"></a>
229### `publicPath` (type: `string`, default: `__webpack_public_path__`)
230
231Custom public path for sprite file.
232
233```js
234{
235 test: /\.svg$/,
236 loader: 'svg-sprite-loader',
237 options: {
238 extract: true,
239 publicPath: '/'
240 }
241}
242```
243
244<a id="plain-sprite"></a>
245### Plain sprite
246
247You can render plain sprite in extract mode without styles and usages. Pass `plainSprite: true` option to plugin constructor:
248
249```js
250{
251 plugins: [
252 new SpriteLoaderPlugin({ plainSprite: true })
253 ]
254}
255```
256
257<a id="sprite-attrs"></a>
258### Sprite attributes
259
260Sprite `<svg>` tag attributes can be specified via `spriteAttrs` plugin option:
261
262```js
263{
264 plugins: [
265 new SpriteLoaderPlugin({
266 plainSprite: true,
267 spriteAttrs: {
268 id: 'my-custom-sprite-id'
269 }
270 })
271 ]
272}
273```
274
275## Examples
276
277See [examples](examples) folder.
278
279## Contributing guidelines
280
281See [CONTRIBUTING.md](CONTRIBUTING.md).
282
283## License
284
285See [LICENSE](LICENSE)
286
287## Credits
288
289Huge thanks for [all this people](https://github.com/JetBrains/svg-sprite-loader/graphs/contributors).
290
291[npm-url]: https://www.npmjs.com/package/svg-sprite-loader
292[version-img]: https://img.shields.io/npm/v/svg-sprite-loader.svg?style=flat-square
293[versions-img]: https://libraries.io/npm/svg-sprite-loader/versions
294[downloads-img]: https://img.shields.io/npm/dm/svg-sprite-loader.svg?style=flat-square
295[deps-url]: https://david-dm.org/JetBrains/svg-sprite-loader
296[deps-img]: https://img.shields.io/david/JetBrains/svg-sprite-loader.svg?style=flat-square
297[dev-deps-url]: https://david-dm.org/JetBrains/svg-sprite-loader?type=dev
298[dev-deps-img]: https://img.shields.io/david/dev/JetBrains/svg-sprite-loader.svg?style=flat-square
299[ci-url]: https://travis-ci.org/JetBrains/svg-sprite-loader
300[ci-img]: https://img.shields.io/travis/JetBrains/svg-sprite-loader.svg?style=flat-square
301[docs-coverage-url]: https://inch-ci.org/github/JetBrains/svg-sprite-loader
302[docs-coverage-img]: https://inch-ci.org/github/JetBrains/svg-sprite-loader.svg?branch=master&style=flat-square