Skip to content

Commit

Permalink
fix: transform useSlots usages into dummy <slot /> in templates (#64
Browse files Browse the repository at this point in the history
)
  • Loading branch information
farnabaz authored Jan 17, 2024
1 parent 1a173aa commit 032ff4a
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
12 changes: 12 additions & 0 deletions playground/components/content/UseSlots.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<template>
<div>
Dummy component to test useSlots
</div>
</template>

<script setup lang="ts">
const slots = useSlots()
const defaultSlot = computed(() => slots.default?.())
</script>
9 changes: 9 additions & 0 deletions playground/components/content/UseSlotsDestructuring.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<template>
<div>
Dummy component to test useSlots
</div>
</template>

<script setup lang="ts">
const { title, default: dd } = useSlots()
</script>
21 changes: 21 additions & 0 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,27 @@ export default defineNuxtModule<ModuleOptions>({
return `<slot ${slotName === 'default' ? '' : `name="${slotName}"`} />`
}
)
// Handle `(const|let|var) slots = useSlots()`
const name = code.match(/(const|let|var) ([a-zA-Z][a-zA-Z-_0-9]*) = useSlots\(\)/)?.[2] || '$slots'
const _slots = code.match(new RegExp(`${name}\\.[a-zA-Z]+`, 'gm'))
if (_slots) {
const slots = _slots
.map(s => s.replace(name + '.', ''))
.map(s => `<slot name="${s}" />`)
code = code.replace(/<template>/, `<template>\n${slots.join('\n')}\n`)
}

// Handle `(const|let|var) { title, default: defaultSlot } = useSlots()`
const slotNames = code.match(/(const|let|var) {([^}]+)}\s*=\s*useSlots\(\)/)?.[2]
// \s*(([a-zA-Z][a-zA-Z-_0-9]*(\s*:\s*[a-zA-Z][a-zA-Z-_0-9]*)?\s*,?\s*)+)\s*
if (slotNames) {
const slots = slotNames
.trim()
.split(',')
.map(s => s.trim().split(':')[0].trim())
.map(s => `<slot name="${s}" />`)
code = code.replace(/<template>/, `<template>\n${slots.join('\n')}\n`)
}

return { component, code }
}
Expand Down

0 comments on commit 032ff4a

Please sign in to comment.