Define components with "require.context" in "<script setup>". #354
Replies: 1 comment
-
Solved this problem with the code below, but I get an error when I try to use the <template>
<component :is="icon" />
</template>
<script lang="ts" setup>
import { kebabCase } from '@/helpers'
import { computed, toRefs } from 'vue'
import type { DefineComponent } from 'vue'
export interface IconComponentsList {
components: Record<string, DefineComponent>
namesForValidator: string[]
}
function getIconsComponents(): IconComponentsList {
const context = require.context('../icons', true, /Icon[A-Z]\w+\.vue$/)
const res = {
components: {} as Record<string, DefineComponent>,
namesForVallidator: [] as string[],
}
for (const key of context.keys()) {
const match = key.match(/\/(\w+)\.\w+$/)
if (match && match[1] && typeof match[1] === 'string') {
const name = kebabCase(match[1].replace('Icon', ''))
res.components[name] = context(key).default
res.namesForVallidator.push(name)
}
}
return res
}
const { components, namesForValidator }: IconComponentsList = getIconsComponents()
const { name } = toRefs(defineProps({
name: {
type: String,
required: true,
validator(v: string) {
return namesForValidator.includes(v) // this line causes error <--------------------------------------
},
},
}))
const icon = computed(() => {
return components[name]
})
</script> Error:
If I remove the |
Beta Was this translation helpful? Give feedback.
-
How can I add components with
require.context
using<script setup>
?The rfc for script setup shows this example. In the example, each component has to be imported.
In the Options API I used this code to collect all the components from a particular folder:
Then I add the resulting
components
object to the options object passed todefineComponent
.All this works fine.
But in the
<script setup>
it's not clear to me how to make it work.Maybe there is (or is planned) some undocumented
defineComponets
compiler macros that would solve this problem?Beta Was this translation helpful? Give feedback.
All reactions