Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue CLI - include image from assets folder in static file

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

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.

App structure:

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

And in _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)
    */
}

Which returns an error with This relative module was not found.

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?

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

Maybe some custom webpack config?

Thanks

like image 743
Vucko Avatar asked Jul 26 '18 05:07

Vucko


People also ask

How do I add images to Vue JS?

How do you upload images to vue. js? First, select a file (make sure to add <input type="file"> to your component template code). Then, you send the file to a server (you can use axios).

What are static assets?

Static assets are object you send to the user that the server does not change. Images are an example of static assets. Rather that create a route for each image or static asset, folders can be declared “static” or “public” in Express and routes will automatically be configured.

How do I import a component into Vue?

STEP 01: First, Import the Child Component into the Parent Component inside script tag but above export default function declaration. STEP 02: Then, Register the Child Component inside the Parent Component by adding it to components object. STEP 03: Finally, Use the Child Component in the Parent Component Template.


1 Answers

You can manage that by :

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

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

like image 139
Saša Šijak Avatar answered Oct 27 '22 09:10

Saša Šijak