Felix
Felix

Reputation: 224

Attaching an SVG to the DOM with Webpack

Currently my company includes a rather large SVG sprite containing various icons in the index.html of our AngularJS web app. The main SVG is hidden by CSS and we display individual icons from the SVG by selecting them by their IDs:

<svg>
  <use xlink:href="#icon-id"></use>
</svg>

We are now trying to reduce the load time of our site by splitting up the SVG and inlining the resulting parts on pages tha need them. Since we are also moving to Webpack to bundle our app, we'd like to specify dependencies for a specific SVG file in an Angular module and then have Webpack insert the content of the SVG -- possibly wrapped in a div -- into the DOM. Is there any way of achieving this with an existing loader? I found the raw-loader which basically exports the content of our SVG. However, I don't know how to chain it with another loader that would insert into the DOM like say the style-loader does.

Any help is greatly appreciated.

Felix

Upvotes: 6

Views: 8779

Answers (3)

mrsum
mrsum

Reputation: 208

Also you can use: https://github.com/mrsum/webpack-svgstore-plugin for that

npm i webpack-svgstore-plugin --save-dev

Upvotes: 1

ptim
ptim

Reputation: 15607

Another option has come out since this question was asked: https://github.com/kisenka/svg-sprite-loader

It's like style-loader but for SVG:

  • Creates a single SVG sprite from a set of images.
  • Raster images support (PNG, JPG and GIF).
  • Custom sprite implementation support.

React examples are provided, and there is a config option for angular:

  • angularBaseWorkaround Adds workaround for issue with combination of and History API which is typical for Angular.js.
// some-component.jsx
import Icon from './icon';
import help from './images/icons/Help.svg';

<Icon glyph={help} />

Upvotes: 2

Felix
Felix

Reputation: 224

I ended up writing my own webpack loader for this problem. You can install the inline-loader through npm. More info can be found at https://www.npmjs.com/package/inline-loader

Upvotes: 1

Related Questions