How to access assets with webpacker gem

Viewed 8983

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?

5 Answers

Since this is tagged with Vue.js I will answer for that. None of the other answers worked with Vue 2.x.

For Attributes

A webpacker require statement returns the full URL of the required asset (resolved based on your resolved_paths inside webpacker.yml). Based on that, you can do something like this:

<img :src="require('images/what-a-pain.png')" alt="Finally working" />

Please note the colon causing the src attribute to be bound to the result of the javascript expression.

You can also use ID anchors by appending them, for example with SVG:

<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg">
    <use :href="require('images/icons.svg') + '#copy'" />
</svg>

Vue templates are generally pre-compiled to javascript equivalents, so a require statement is needed to pull the assets in at compile time, not runtime.

For CSS urls, scoped or not

Simply use a tilde ~ and a path. The path must be relative to either the file including it or the resolved_paths from webpacker.yml.

.relative-pathed {
    background: url(~../../../assets/images/quitethepath.svg) center center no-repeat;
}
.works-after-editing-webpackeryml {
    background: url(~images/quitethepath.svg) center center no-repeat;
}

For this usage there is no need to require() the asset.

Please note: there is a difference in paths between development and production, especially if Sprockets is also used. Simply doing src="/assets/image.png" will sometimes work in developement, but not production.

Related