简体   繁体   中英

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

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

您也可以使用: https//github.com/mrsum/webpack-svgstore-plugin

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM