Parcel plugin which generate a SVG sprite with <symbol> elements and inject it in built html
npm install parcel-plugin-svg-sprite> warning : this plugin overwrite HTMLPackager, it can be in conflit with other plugin which also overwrite HTMLPackager.
> Until version 1.1.2 files in an assets folder or subfolder wasn't injected in sprite to have the possibility to use svg files in css (css can't reference a svg symbol).
> Since version 1.2.0 you can use options include and exclude to define path patterns you don't want to inject in sprite and import them as file url.
> This can be usefull to import svg font in css or to use svg file in css background-image.
bash
yarn add -D parcel-plugin-svg-spriteor with npm
npm install -D parcel-plugin-svg-sprite
`$3
Once the plugin is installed, you can import svg like this :In html file :
`html
...
...
...
...
`In javascript file :
`javascript
import checkmark from './icons/checkmark.svg';const icon =
;
`Or with JSX :
`javascript
import React from 'react';
import checkmark from './icons/checkmark.svg';const icon = (
);
`When you import a svg, you get the id of the symbol generated in built sprite. This is why you can use it as
xlink:href attribute.#### HTML input example:
`html
Document
`#### Generated HTML expected
`html
Document
`$3
This plugin has 2 options to give the possibility to handle specific cases.
There are 2 ways to set plugin options:
- add an object
svgSpriteOptions in package.json of the project
- create svgSprite.config.js file which export an object at the root of your project.> options set in
svgSprite.config.js overwrite options set in package.jsonexclude
string[]
List of glob patterns which should not be included in svg sprite and should be imported as file url (like Parcel's default behavior).
This can be usefull if you need to import file in css (for font or background-image).
example (to avoid inject files from assets folder in svg sprite):
`json
// package.json
"name": "my-package-name",
...
"svgSpriteOptions": {
"exclude": ["/assets//*"]
}
`include
string[]
List of glob patterns which can be injected in svg sprite.
If the option isn't set all svg file which aren't exluded will be injected in svg sprite.
If a file path matches with both include and exclude options, the path will be excluded.
example:
`json
// package.json
"name": "my-package-name",
...
"svgSpriteOptions": {
"include": ["src/*/"]
}
`getSymbolId
(filePath, fileContent, fileHash) => string (only in svgSprite.config.js)
Give the possibilty to define how svg symbol ids are generated. By default the svg id will be the hash of file content.
exemple:
`js
// svgSprite.config.js
const path = require('path');module.exports = {
getSymbolId: (filePath, fileContent, fileHash) => {
return path.basename(filePath, '.svg');
},
};
``