svg-asset-loader
TypeScript icon, indicating that this package has built-in type declarations

1.2.0 • Public • Published

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

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

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

Package Sidebar

Install

npm i svg-asset-loader

Weekly Downloads

14

Version

1.2.0

License

MIT

Unpacked Size

16.4 kB

Total Files

25

Last publish

Collaborators

  • heshanera