简体   繁体   English

使用Webpack将SVG附加到DOM

[英]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. 目前,我的公司在AngularJS网络应用的index.html中包含一个相当大的SVG子图形,其中包含各种图标。 The main SVG is hidden by CSS and we display individual icons from the SVG by selecting them by their IDs: CSS隐藏了主要的SVG,我们通过按ID进行选择来显示SVG中的各个图标:

<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. 我们现在正在尝试通过拆分SVG并在需要它们的页面上内嵌结果部分来减少网站的加载时间。 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. 由于我们还将移动到Webpack来捆绑应用程序,因此我们想在Angular模块中为特定SVG文件指定依赖项,然后让Webpack将SVG的内容(可能包装在div中)插入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. 我发现原始加载程序基本上可以导出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 自问这个问题以来出现了另一个选择: https//github.com/kisenka/svg-sprite-loader

It's like style-loader but for SVG: 就像样式加载器,但对于SVG:

  • Creates a single SVG sprite from a set of images. 从一组图像创建单个SVG子画面。
  • Raster images support (PNG, JPG and GIF). 光栅图像支持(PNG,JPG和GIF)。
  • Custom sprite implementation support. 自定义精灵实现支持。

React examples are provided, and there is a config option for angular: 提供了React示例,并且为angular提供了一个配置选项:

  • angularBaseWorkaround Adds workaround for issue with combination of and History API which is typical for Angular.js. angularBaseWorkaround添加了与Angular.js典型的和History API结合使用时出现的问题的解决方法。
// 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. 我最终为这个问题写了自己的webpack加载器。 You can install the inline-loader through npm. 您可以通过npm安装inline-loader。 More info can be found at https://www.npmjs.com/package/inline-loader 可以在https://www.npmjs.com/package/inline-loader中找到更多信息

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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