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
Once you start your application, Webpack will do its thing and you don't need to worry about your SVGs anymore. You can put your SVG files anywhere in your src/ folder and import them wherever you need them as React components. This method is generally referred to as inline-svg .
How to use inline SVG images. SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document.
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} />
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With