Created
February 24, 2023 13:41
-
-
Save johannschopplich/552d84d4a34be17740fe17f51c6a603f to your computer and use it in GitHub Desktop.
Auto-import icons from `assets` in Nuxt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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