How to access assets with webpacker gem

Alexey Poimtsev picture Alexey Poimtsev · Aug 7, 2017 · Viewed 7.5k times · Source

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?

Answer

sandrew picture sandrew · Sep 5, 2017

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.