1

I followed this solution to make alias @ work:

My vite.config.js:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: [
      { find: '@', replacement: path.resolve(__dirname, 'src') }
    ],
  },
})

This works:

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

This doesn't work:

<img src="@/assets/logo.png" srcset="@/assets/[email protected] 2x">

Here is how my output in browser looks like:

<img
  src="/src/assets/logo.png"
  srcset="/src/views/@/assets/[email protected] 2x"
>

3 Answers 3

5

It looks like @vue/compiler-sfc has a bug, introduced in v3.0.0-beta.9 when adding support for absolute URLs in srcset. This bug bypasses the transformation that would've resolved the asset URLs in srcset. (Reported in GitHub issue vuejs/vue-next#4819)

A workaround I found was to manually create a srcset with the asset URLs explicitly resolved:

<template>
  <img :srcset="srcset" />
</template>

<script setup>
import logo2x from '@/assets/[email protected]'
import logo3x from '@/assets/[email protected]'

const srcset = `${logo2x} 2x, ${logo3x} 3x`
</script>

Or using dynamic imports, which may be helpful if you need to update srcset dynamically:

<template>
  <img :srcset="srcset" />
</template>

<script setup>
import { ref } from 'vue'

const srcset = ref(null)
Promise.all([
  import('@/assets/[email protected]'),
  import('@/assets/[email protected]')
]).then(([{ default: logo2x }, { default: logo3x }]) => {
  srcset.value = `${logo2x} 2x, ${logo3x} 3x`
})
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

is this issue know or reported to vite team? will there any easy fix soon?
@Syed I reported the bug in github.com/vuejs/vue-next/issues/4819
0

Did you try using the v-binding for srcset.

<img 
  src="@/assets/logo.png" 
  :srcset="require('@/assets/[email protected]') + ' 2x'"/>

1 Comment

Thanks for your help, but that did not help. I am getting this error: Uncaught (in promise) ReferenceError: require is not defined and more over I was looking for solution without using require().
0

Unless you are not very specific to keep images in ./src/assets/images folder, there is a simple fix and that would be to move your images to ./public/assets/image folder and refer it like:

<img src="/assets/images/img-01.png"
     srcset="/assets/images/[email protected] 2x">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.