vue -vite |静态SVG资产
在我的Vue Vite应用程序中,我尝试将SVG文件用作HTML元素中的SRC属性。
<img class="..." src="/src/assets/images/bg/main-banner.svg" alt="Background">
在开发中,它可以按预期工作。 在生产中,图像的SRC属性为 [对象对象] 。我尝试了从
谢谢。
In my Vue vite app, I am trying to use svg file as src attribute in html element.
<img class="..." src="/src/assets/images/bg/main-banner.svg" alt="Background">
In development, it works as expected.
In production, the src attribute of the image is [object Object]. I tried every approach from Vite documentation , but none of these could fix the issue. I am using vite-svg-loader, so I can use svg files as Vue Components. Could this be somehow related to the issue?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
vite-svg-loader
vite-svg-loader
原因*。svg
默认情况下解决为VUE组件,将转换为一个转换为一个&lt; img&gt; .src
属性的字符串,导致[Object Object]
。为了将
*。svg
作为URL加载,您可以将加载程序配置为导入url
默认情况下:With
vite-svg-loader
vite-svg-loader
causes*.svg
to resolve as Vue components by default, which would be converted into a string for the<img>.src
attribute, resulting in[object Object]
.To load the
*.svg
as a URL instead, you can either configure the loader to import theurl
by default:demo 1
...or use a
url
import param:demo 2
Without
vite-svg-loader
If you just want to get the
*.svg
's URL, you actually don't needvite-svg-loader
, as that's a built-in feature. Removingvite-svg-loader
should resolve the issue:demo 3
尝试将其导入作为模块,然后将其绑定到
src
属性:Try to import it as module then bind it to the
src
attribute :我也有一个类似的问题,我想导入许多横幅,例如
main-banner1.svg
,main-banner2.svg
,等等,所以我尝试了试图用另一种视图重新使用横幅时的问题。
我的解决方案是将SVG文件移至
public
文件夹,并使用路径为:请注意,这也可以防止VITE添加散布到文件名。
Note :也可以在
public
文件夹中的子文件夹中组织所有内容以使用原始路径。I had a similar issue, I wanted to import many banners, like
main-banner1.svg
,main-banner2.svg
, and so on, so I triedbut I had a problem when trying to re-use the banner with another view.
My solution was to move the svg file to the
public
folder and use the path as:Note that this also prevents Vite from adding hashing to the file names.
Note: It is also possible to organize everything in sub-folders in the
public
folder to use the original path.