【问题标题】:Unable to import SVG file into React无法将 SVG 文件导入 React
【发布时间】:2017-07-06 11:11:06
【问题描述】:

我正在使用 React v15.4.1。我已经关注了this solution,但是在应该呈现组件的地方,我只得到了一个像这样的字符串https://localhost:3001/dist/7553ed8d42edb0d73754cd9a5dea2168.svg

我的 React 组件设置如下:

import theSVGicon from 'path/to/icon.svg';
...
<span dangerouslySetInnerHTML={{ __html: theSVGicon }} />

其他说明:

  1. 当我将图像作为src 包含在image 中时,图像呈现良好,如下所示:&lt;img src={theSVGicon}/&gt;
  2. this 页面底部的代码确实有效: <svg viewBox="0 0 64 64" width="64" height="64" fill="currentcolor"> <path d="M 28.495430026136273 0 L 35.504569973863724 0 L 37.22908963117581 ... 0 0 0 32 20"></path> </svg>
  3. 遵循this 解决方案,我确实看到了一个svg 组件以及其他属性。我也看到了它应该在哪里的间距,但它是空白的。更多详情:

image link: http://imgur.com/a/6GxDD

  1. 理想情况下,我想像上面 (3) 那样设置我的 svg 图像,这样我就可以调整 viewBoxheight 等属性,这在最新的 React 版本中受支持。

我的装载机有问题吗?我正在使用 Webpack 并使用 webpack-isomorphic-tools 呈现服务器端。我不想对此进行过多研究,因为它确实可以与 img 一起使用,而且我有应该处理基于 boilerplate 早期版本的 SVG 的代码:

dev.config.js

...
module: {
    loaders: [
      ...
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml" },
      { test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url-loader?limit=10240' }
    ]
  },
...

webpack-isomorphic-tools.js

...
assets: {
    ...
    svg: {
      extension: 'svg',
      parser: WebpackIsomorphicToolsPlugin.url_loader_parser
    },
...

我最后的努力是重做并关注this

【问题讨论】:

    标签: html reactjs svg ecmascript-6 loader


    【解决方案1】:

    使用svg-inline-react 作为加载器并将svg 加载为内联

    { test: /\.svg$/, loader: 'svg-inline' }
    

    指定 svg-inline 加载器,它应该与您的下一行一起使用

    <span dangerouslySetInnerHTML={{ __html: UpvoteFist }} />
    

    但如果只有加载器对您不起作用,请遵循他们给出的指导方针

    import InlineSVG from 'svg-inline-react'; // ES2015
    

    .......

     <InlineSVG src={require("svg-inline!icon.svg")} /> // Use with loader
    

    【讨论】:

    • 将它作为src 放在img 中对我有用,但我想将它呈现为svg-inline。
    • 是的,svg-inline 加载器不适合我。然后它会抛出一个错误,即无法解析我的一个节点模块中的字体真棒 svg 文件。您的第二个建议不适用于很多 svg-inline-loader doesn't exist 不存在错误。如果你有的话,我想知道你的 webpack-isomorphic-tools.js 文件是什么样子的?我认为本指南是我让它发挥作用的最接近的机会:github.com/peter-mouland/react-lego/wiki/Importing-SVGs。我需要弄清楚的主要事情之一是为什么我的svg 不包含在图像中:扩展 [...
    • 无论require-直接加载加载器还是在我的 webpack 配置中设置它,我都会遇到同样的错误:[1] [piping] 给出的错误是:SyntaxError: Unexpected token &amp; [1] at exports.runInThisContext (vm.js:53:16) [1] at Module._compile (module.js:373:25) [1] at Object._module2.default._extensions.(anonymous function) [as .webpack-loaders] (/path/to/app/node_modules/webpack-isomorphic-tools/node_modules/require-hacker/babel-transpiled-modules/require hacker.js:274:11)
    • 我的解决方案可能就在这里,因为我遇到了类似的问题并使用了相同的样板应用程序:github.com/halt-hammerzeit/webpack-isomorphic-tools/issues/59
    猜你喜欢
    • 2020-06-24
    • 2019-03-23
    • 2020-10-18
    • 1970-01-01
    • 2021-09-30
    • 2018-08-31
    • 2019-10-23
    相关资源
    最近更新 更多