Open mklueh opened 2 years ago
Duplicate of #86
In Nuxt 3, you don't need svg-module
, but can instead create a custom component utilizing Vite's glob import:
<template>
<span v-if="icon" class="h-[1em] w-[1em]" v-html="icon" />
</template>
<script setup lang="ts">
const props = defineProps<{
name?: string
}>()
// Auto-load icons
const icons = Object.fromEntries(
Object.entries(import.meta.glob('~/assets/images/*.svg', { as: 'raw' })).map(
([key, value]) => {
const filename = key.split('/').pop()!.split('.').shift()
return [filename, value]
},
),
)
// Lazily load the icon
const icon = props.name && (await icons?.[props.name]?.())
</script>
Isn't Vite only used during development? Unless this feature is not Vite specific...
@rchl No, Vite is used during development as the dev server and also as the bundler for production builds. Nuxt 3 is built upon Vite. As linked before, import.meta.glob
is a Vite-specific feature.
It says to support both webpack and vite as bundlers. I'm not sure which one in which cases or whether it's user's choice but I guess that in some cases the suggested code wouldn't work.
Good point. If you opt in for webpack in Nuxt 3, the component would not work, since the glob import is a Vite-specific feature. Honestly, the use-cases for webpack are probably little. The overall experience is just lacking behind Vite. That's why Vite is the default in Nuxt 3 as well as optimized for it. Some modules don't even support webpack in the first place (not saying that's a good thing).
I'm confused. What worked with Nuxt 2 does not work (or sometimes only when hot reload triggers the page refresh)
What I've tried so far:
1. Direct require in v-html
result:
2. Via await import (not according to the docs)
result:
However, the odd thing is, if I comment that line out let image = (await import("../assets/" + props.icon + "?raw")).default; and let the page load, and then uncomment it, it will load the icon
3. Via import but not with await
result: shows [OBJECT PROMISE]
4. With require in script tag
result:
**5. With compute and require
result:
6. With compute and import and async
result: shows [OBJECT PROMISE]
I'm not sure what else I could try and I don't see a reason why this happens.
Maybe I should add, that the component is not located in the actual Nuxt application, but a Nuxt library module, and the assets are located in the library as well.
I'd appreciate any help