Search code examples
typescriptvue.jsjsdocvue-composition-api

How to use JSDoc to document a Vue component with script setup?


I'm building a Vue library with TypeScript. I'd like to export the documentation of the components, like I do with ordinary functions.

Previously we would do this:

<script>
/**
 * This is the documentation of my component.
 */
export default {
}
</script>

<template></template>

But now with script setup:

<script setup lang="ts">
</script>

<template></template>

How do we document the component?


Solution

  • With <script setup> you can't use JSDoc on the component export.

    It's a compiler syntaxic sugar that gets out the export of the setup function, so you obviously can't comment a function that is "generated" by the compiler.

    If you really needs JSDoc, you should use a regular <script> with a default export :)

    <script>
    /** This is my nice component documentation */
    export default {
      name: 'MyComponent',
      setup() {
        // your code
      }, 
    }
    </script>
    

    Also works with the typescript defineComponent wrapper:

    <script>
    import { defineComponent } from 'vue'
    
    /** This is my nice component documentation */
    export default defineComponent({
      name: 'MyComponent',
      setup() {
        // your code
      }
    })
    </script>
    

    EDIT: as mentionned by @EstusFlask in the comments, you can mix both <script setup> and <script> on a SFC component (see docs) So you can use the regular script to expose your JSDoc.

    <script setup>
    // component setup. Takes priority over the eventual `setup()` function of the export object in <script>.
    </script>
    
    <script>
    /** This is my nice component documentation */
    export default {
      name: 'MyComponent',
    }
    </script>