Skip to content

Instantly share code, notes, and snippets.

@johannschopplich
Created February 24, 2023 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johannschopplich/552d84d4a34be17740fe17f51c6a603f to your computer and use it in GitHub Desktop.
Save johannschopplich/552d84d4a34be17740fe17f51c6a603f to your computer and use it in GitHub Desktop.
Auto-import icons from `assets` in Nuxt
<template>
<span
v-if="icon"
:class="[
'children-[svg]:h-full children-[svg]:w-full',
defaultStyles && 'inline-block h-[1em] w-[1em] align-middle',
]"
v-html="icon"
/>
</template>
<script setup lang="ts">
import { kebabCase } from 'scule'
const props = withDefaults(
defineProps<{
name?: string
defaultStyles?: boolean
}>(),
{
name: undefined,
defaultStyles: true,
}
)
// Auto-load icons
const icons = Object.fromEntries(
Object.entries(import.meta.glob('~/assets/icons/*.svg', { as: 'raw' })).map(
([key, value]) => {
const filename = key.split('/').pop()!.split('.').shift()
return [filename, value]
}
)
)
const icon = ref<string | undefined>()
const iconName = computed(() =>
props.name ? kebabCase(props.name) : undefined
)
watch(iconName, loadIcon)
await loadIcon(iconName.value)
async function loadIcon(name?: string) {
if (name) {
icon.value = await icons?.[name]?.()
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment