Vue CLI - 在静态文件中包含资产文件夹中的图像 [英] Vue CLI - include image from assets folder in static file

查看:30
本文介绍了Vue CLI - 在静态文件中包含资产文件夹中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在某些静态 .scss 文件中包含 assets/ 文件夹中的图像作为 background-image>?

Is it possible to include an image, which is in assets/ foder, in some static .scss file, as a background-image?

我有一个 _buttons.scss 部分,有些按钮有一个图标,我想将其添加为 background-image.图标位于 src/assets/ 文件夹中.

I have a _buttons.scss partial and some buttons have an icon, which I'd like to add as a background-image. The icons are located in src/assets/ foder.

应用结构:

- src
  - assets
    some_icon.svg
  - components
  - scss
    _buttons.scss
    main.scss
  - views
  App.vue
  main.js
  router.js

_buttons.scss 中:

.some-selector {
    background-image: url(../assets/some_icon.svg)

    /* also tried
    background-image: url(./assets/some_icon.svg)
    background-image: url(/assets/some_icon.svg)
    background-image: url(assets/some_icon.svg)
    */
}

返回一个错误,找不到这个相关模块.

我知道我可以简单地在我的组件或主 App.vue 中添加这些样式(范围与否),但是,我想知道如果没有它是否可以实现?

I know I can simply add those styles (scoped or not) in my component, or in main App.vue, however, I was wondering if this can be achieved without that?

我也知道我可以将这些图标添加到我的 public 文件夹中,但我希望这些图标保留在 assets/ 文件夹中.

I know also that I can add those icons in my public folder but I would like for the icons to remain in the assets/ folder.

$ vue -V
$ 3.0.0-rc.5

也许是一些自定义的 webpack 配置?

Maybe some custom webpack config?

谢谢

推荐答案

您可以通过以下方式管理:

You can manage that by :

background-image: url('~@/assets/some_icon.svg');

这里的关键是使用 ~@ 作为前缀.以 ~ 为前缀的 URL 被视为模块请求.如果您想利用 Webpack 的模块解析配置,则需要使用此前缀.例如,如果 src 文件夹的解析别名等于 @,如果您使用 vue-cli3,您会这样做,您可以使用这种类型的 URL 强制 Webpack 解析到所需的资源中资产文件夹.更多信息在这里:处理静态资产

Key here is using ~@ as a prefix. URLs prefixed with ~ are treated as a module request. You need to use this prefix if you want to leverage Webpack's module resolving configurations. For example if you have a resolve alias for src folder equal to @, which you do if you use vue-cli3, you can use this type of URL to force Webpack to resolve to the needed asset in the assets folder. More info here: handling static assets

这篇关于Vue CLI - 在静态文件中包含资产文件夹中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆