Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access assets with webpacker gem

Could you explain me how to access assets from webpacker gem within vue.js components? For example - how to create div with background image. I've tried use /app/assets/images and /app/javascripts/assets folders but images is only available in template section, but not in style section :(

in my case

<template>
    <div id="home">
        <div id="intro">
            <img src="assets/cover-image-medium.png" alt="">
        </div>
    </div>
</template>

works fine, but

<style scoped>
    #intro {
        height: 200px;
        background: url("assets/cover-image-medium.png");
    }
</style>

not working :(

Whats wrong?

like image 675
Alexey Poimtsev Avatar asked Aug 07 '17 15:08

Alexey Poimtsev


People also ask

What is Webpacker gem?

Webpacker gem creates the application pack in the form of this application. js file under app/javascript/packs . If you remember the assets pipeline, this file is equivalent to the app/assets/javascripts/application. js file.

What is Webpacker in Ruby?

Webpacker is a Rails wrapper around the webpack build system that provides a standard webpack configuration and reasonable defaults.


1 Answers

New Rails' webpacker stuff is pretty raw, so that's the configuration that works for me:

config/webpacker.yml (for webpacker 3):

resolved_paths: ['app/javascript/images', 'app/javascript/src']
compile: false
# ...

JS files:

/app
  /javascript
    /packs
      # only entry point files
      vue_application.js
    /src
      some_component.vue
    /images
      logo.svg

in component:

<script>
import 'images/logo.svg'
</script>

in template:

<img src='~images/logo.svg' />

point the tilde here - it means that the image is a module dependency

in CSS:

<style lang='sass'>
#app
  background: url('../images/logo.svg')
</style>

For some reason tilde does not work here, so relative path is used.

like image 179
sandrew Avatar answered Oct 12 '22 14:10

sandrew