Webpack loader for processing SVG files. Loader options allows 3 options: embedding SVGs directly into the HTML, combining SVGs into a single spritesheet injected into the HTML, or extracting SVGs into an external sprite file for linking.
npm i svg-asset-loader
Spritesheet injection 🔗
// webpack.config.js
const config = {
...
module: {
rules: [
{
test: /\.svg$/,
loader: 'svg-asset-loader',
},
],
},
...
};
export default config;
// index.js
import icon from '../../assets/stop-watch.svg';
import icon2 from '../../assets/coconut-tree.svg';
...
<div>
<svg viewBox="${icon.viewBox}">
<use href="#${icon.id}"></use>
</svg>
<svg viewBox="${icon2.viewBox}">
<use href="#${icon2.id}"></use>
</svg>
</div>
...
Inline 🔗
// webpack.config.js
const config = {
...
module: {
rules: [
{
test: /\.svg$/,
loader: 'svg-asset-loader',
options: {
strategy: 'inline',
},
},
],
},
...
};
export default config;
// index.js
import icon from '../../assets/stop-watch.svg';
import icon2 from '../../assets/coconut-tree.svg';
...
<div>
<img src=${icon} height="100px" width="100px" />
<img src=${icon2} height="100px" width="100px" />
</div>
...
Extraction and linking 🔗
// webpack.config.js
const config = {
...
module: {
rules: [
{
test: /\.svg$/,
loader: 'svg-asset-loader',
options: {
strategy: 'extract',
outFile: './public/spritesheet.svg',
prefix: './spritesheet.svg',
},
},
],
},
...
};
export default config;
// index.js
import icon from '../../assets/stop-watch.svg';
import icon2 from '../../assets/coconut-tree.svg';
...
<div>
<svg viewBox="${icon.viewBox}">
<use href=${icon.href}></use>
</svg>
<svg viewBox="${icon2.viewBox}">
<use href=${icon2.href}></use>
</svg>
</div>
...
Property | Default | Description |
---|---|---|
strategy | inject |
SVG loading strategy Available strategies: inject , extract , inline
|
outFile | sprite.svg |
File name for the generated svg spritesheet To be used with the extract strategy |
prefix | sprite.svg |
File path to access the generated spritesheet To be used with the extract strategy href: {prefix}#{id}
|
# Build the loader
npm run build
# Go to the example directory
cd examples/inlineSVGs/
# Start the server
npm run start