npm.io
1.2.0 • Published 1 year ago

svg-asset-loader

Licence
MIT
Version
1.2.0
Deps
0
Size
16 kB
Vulns
0
Weekly
0

svg-asset-loader

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.

Test Build Publish  Node  NPM  License: MIT  Minzip 

Installation

npm i svg-asset-loader

Usage

// 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>
...
// 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>
...
// 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>
...

Loader Options

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}

Running Examples Locally

# Build the loader
npm run build

# Go to the example directory
cd examples/inlineSVGs/

# Start the server
npm run start

Keywords