Skip to content

Commit

Permalink
feat: detect $slots usages in template (#26)
Browse files Browse the repository at this point in the history
  • Loading branch information
farnabaz authored Jul 18, 2022
1 parent 6e70ad3 commit ec35351
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/utils/parseTemplate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { SFCDescriptor } from '@vue/compiler-sfc'
import { compileTemplate } from '@vue/compiler-sfc'

export function parseTemplate (id: string, descriptor: SFCDescriptor) {
const slots = []
if (!descriptor.template) {
return {
slots: []
Expand All @@ -25,7 +26,21 @@ export function parseTemplate (id: string, descriptor: SFCDescriptor) {
]
}

// Detect `$slots` usage
const $slots = template.source.matchAll(/\$slots(\.([-_\w]+)|\[['"]([-_\w]+)['"]\])/g)
let $slot = $slots.next()
while (!$slot.done) {
slots.push({
name: $slot.value[2] || $slot.value[3]
})
$slot = $slots.next()
}

// Detect `<slot>` usage
const slotsAst = findSlots(template.ast.children)
slots.push(...slotsAst)

return {
slots: findSlots(template.ast?.children || [])
slots
}
}
2 changes: 2 additions & 0 deletions test/basic-component.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ describe('Basic Component', async () => {

test('Slots', () => {
expect(slots).toEqual([
{ name: 'variable' },
{ name: 'foo-bar' },
{ name: 'default' },
{ name: 'nuxt' }
])
Expand Down
3 changes: 3 additions & 0 deletions test/fixtures/basic/components/BasicComponent.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
<slot />
<hr>
<slot name="nuxt" />

<SomeComponent :prop="$slots.variable" />
<SomeComponent :prop="$slots['foo-bar']" />
</div>
</template>

Expand Down

0 comments on commit ec35351

Please sign in to comment.