5

my vue app, make img-src binding with alias. it running direct use.

<img src="@/assets/search.png" />

But, this code make component, alias not resolve.

<template>
  <div class="button-card">
    <img :src="src">
  </div>
</template>

<script>
export default {
  name: 'Button Card',
  props: {
    src: {
      type: String,
    },
  },
};
</script>

With component build result html:

<div class="button-card">
  <img src="@/assets/search.png">
  <!-- should be with resolve: src/assets/search.png -->
</div>

Webpack alias define config:

resolve: {
  extensions: ['.js', '.vue', '.json'],
  alias: {
    'vue$': 'vue/dist/vue.esm.js',
    '@': resolve('src'),
  }
},

Why this code not resolve? or what can I do to make it run?

myazarc
  • 67
  • 1
  • 6

3 Answers3

6

I think that should use data instead of props (you aren't creating a new component and sending the props to it).

You could try with:

<img :src="require('@/assets/search.png')" />

That is a shorthand for:

<template>
  <div id="app">
    <img :src="image" />
  </div>
</template>

<script>
import image from "@/assets/search.png"


export default {
    data: function () {
        return {
            image: image
        }
    }
}
</script>

Here and here you could see how it works and similar problems.

Hope it helps!

JP. Aulet
  • 4,375
  • 4
  • 26
  • 39
1

In short, We can alter transformAssetUrls option of Vue loader to archive this.

Perhaps it's "a little bit" too late, but I decide to leave this comment for someone like me who encounter the similar issue.

After some search and study, I figure out this is webpack loader's work, vue-loader to be specifically. As Vue loader is processing template, it would transforms url of certain attributes of certain tags, which can be configured by transformAssetUrls.

For more detail, you can refer to Asset URL Handling of Vue loader.

James Chen
  • 305
  • 3
  • 7
0

I believe webpack aliases only work in imports, see https://webpack.js.org/configuration/resolve/#resolve-alias:

Create aliases to import or require certain modules more easily. For example, to alias a bunch of commonly used src/ folders:

In your case @/assets/search.png is just a plain string.

I guess you could use dynamic import() function here, something like: return () => import(this.src).

pawel
  • 513
  • 8
  • 15
  • 1
    thanks, i load dynamic data. i use static , working. but with props not resolve, be direct string. – myazarc Jun 26 '18 at 13:11
  • How about putting your images in a directory that is going to be served directly by your server and just using their url in src. No need to import anything then. Something like . – pawel Jun 26 '18 at 14:34