N
Nuxt9mo ago
ManUtopiK

How to check if a composable exists ?

I want to check if a composable exists in a component. With import { myComposable } from '#imports', importing the composable throw an error and break nuxt if the composable doesn't exist.
6 Replies
Dragofafmir
Dragofafmir9mo ago
Did you try to try catch an const { myComposable } = await import('./path/to/myComposable'), try to use it or catch it ? Something like this
<script setup lang="ts">
const composableLoaded = ref(false)

const loadMyComposable = async () => {
try {
const { myComposable } = await import('./path/to/myComposable')
myComposable()
composableLoaded.value = true
} catch (error) {
console.error("...", error)
composableLoaded.value = false
}
}

onMounted(() => {
loadMyComposable()
})
</script>
<script setup lang="ts">
const composableLoaded = ref(false)

const loadMyComposable = async () => {
try {
const { myComposable } = await import('./path/to/myComposable')
myComposable()
composableLoaded.value = true
} catch (error) {
console.error("...", error)
composableLoaded.value = false
}
}

onMounted(() => {
loadMyComposable()
})
</script>
ManUtopiK
ManUtopiKOP7mo ago
I reply a long time ago. First, thank you for your response. It looks fine but can serve my purpose. In fact, I use nuxt layers. I want to check in a component of a layer if the composable exists. So, I can't rely on path/to/myComposable because the composable is outside the package. Using const { myComposable } = await import('#imports') break nuxt build if the composable doesn't exist. Any other idea to do that ?
handshake
handshake7mo ago
I'm just curious, but in what situation would this happen? If you're expecting to use a composable, didn't you create it already?
ManUtopiK
ManUtopiKOP7mo ago
I have a layer with some components shared between two apps. I want the behaviour of the components to be different on one app and use a composable if it presents. Another use case I have for this. I want to release a library and make it open source. This library contains several components with some text and I want to provide translation with i18n. How to check in my components if i18n composable is here and translate text ? Or provide default EN text if there's no i18n composable ? Of course, I don't want to ship i18n in my library.
Orbis
Orbis7mo ago
@ManUtopiK you can maybe use a Provider component to wrap your App and provide and inject your config
ManUtopiK
ManUtopiKOP7mo ago
Ah yes. Thanks for your tip. I will take a try...
Want results from more Discord servers?
Add your server