Syed
Syed

Reputation: 16513

Vite Vue-3 - project @ not working for srcset

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"
>

Upvotes: 1

Views: 2920

Answers (3)

tony19
tony19

Reputation: 138286

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>

Upvotes: 5

Syed
Syed

Reputation: 16513

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">

Upvotes: 0

Tony Tin Nguyen
Tony Tin Nguyen

Reputation: 345

Did you try using the v-binding for srcset.

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

Upvotes: 0

Related Questions