在Astro中导入SVG文件并在不使用<img />标签的情况下使用它。

huangapple go评论116阅读模式
英文:

Import SVG file in Astro and use it without the <img /> tag

问题

有没有一种方法可以在 Astro 文件中直接使用 SVG 文件,而不使用<img />标签。我想要这样的效果:

import Logo from "./logo.svg"

然后像这样使用它:

<Logo />

我尝试过这样做,但没有成功。

英文:

Is there a way to use and SVG file in an Astro file directly without using the &lt;img /&gt; tag. I want something like this:

import Logo from &quot;./logo.svg&quot;

and then use it like this:

&lt;Logo /&gt;

I tried that doing it like that but it didn't work.

答案1

得分: 11

你可以在文件扩展名后添加?raw来更改导入。然后,使用&lt;Fragment set:html={Logo} /&gt;来内联CSS。请参考:这篇文章Astro文档

英文:

You can change the import to add ?raw after the file extension. Then, use &lt;Fragment set:html={Logo} /&gt; to inline the css. See: this post and the Astro docs

答案2

得分: 1

我最终使用了一个名为astro-icon的npm包,我真的很喜欢它,它解决了我的问题。

首先,我在src/下创建了一个名为icons的文件夹,并将我的图标放在其中。然后像这样使用它:

import { Icon } from "astro-icon"

<Icon name={icon_name} />
英文:

I ended up using an npm package called astro-icon which I really liked and it solved my problem.

First, I created a folder name icons in src/ and put my icons inside. Then use it like this:

import { Icon } from &quot;astro-icon&quot;

&lt;Icon name={icon_name} /&gt;

答案3

得分: 1

你可以使用这样的代码而无需任何插件。

---
import loaderEyes from &quot;svgs/loader-eyes.svg?raw&quot;; 
---
&lt;div class=&quot;loader__eyes-container&quot;&gt;
  &lt;Fragment set:html={loaderEyes} /&gt;
&lt;/div&gt;
英文:

You can use code like this without any plugin.

---
import loaderEyes from &quot;svgs/loader-eyes.svg?raw&quot;; 
---
&lt;div class=&quot;loader__eyes-container&quot;&gt;
  &lt;Fragment set:html={loaderEyes} /&gt;
&lt;/div&gt;

答案4

得分: 0

我已经使用了 "astro-icon" 包。您可以在他们的文档中查看如何在您的HTML中加载本地SVG。

基本上只需:

  • 在src目录内创建一个图标文件夹。
  • 在src/icons内创建新的SVG文件,例如 "logo.svg"。
  • 您现在可以在Astro文件中使用 <Icon name="logo" /> 来加载您的SVG。

在这里阅读更多信息:
https://github.com/natemoo-re/astro-icon#local-icon-packs

Astro关于资产的文档:
https://docs.astro.build/en/guides/assets/#move-your-images-to-srcassets

英文:

I have used "astro-icon" package. You can see in their docs how to load local svgs in your html.

Basically just:

  • Create a icon folder inside src directory.
  • Inside src/icons create new svg file. ie. "logo.svg"
  • You can now use &lt;Icon name=&quot;logo&quot; /&gt; in astro files to load your svg.

Read more here:
https://github.com/natemoo-re/astro-icon#local-icon-packs

Astro docs on assets:
https://docs.astro.build/en/guides/assets/#move-your-images-to-srcassets

huangapple
  • 本文由 发表于 2023年4月19日 16:24:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76052260.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定