Endre Szabó
Endre Szabó

Reputation: 584

Dynamic assets in Nuxt / vite

I can load images dynamically from a folder in Nuxt (+ webpack) simply with a method like:

getServiceIcon(iconName) {
  return require ('../../static/images/svg/services/' + iconName + '.svg');
}

I moved to Vite, and require is not defined here (using rollup). How can I solve this, with nuxt / vite? Any idea?

Upvotes: 6

Views: 4311

Answers (1)

tony19
tony19

Reputation: 138226

You can use import() like this:

const getServiceIcon = async iconName => {
  const module = await import(/* @vite-ignore */ `../../static/images/svg/services/${iconName}.svg`)
  return module.default.replace(/^\/@fs/, '')
}

demo 1: Vue 3 Composition API

demo 2: Vue 3 Options API

demo 3: Vue 2 Composition API

demo 4: Vue 2 Options API

Upvotes: 9

Related Questions