·
1 min read

Vue Tip: Split Your SFC into Multiple Files

Vue Tip: Split Your SFC into Multiple Files Image

Vue provides a special file format to combine the template, logic, and styling of a component in a single file. This format is called Single-File Component (SFC) also known as *.vue file.

Component.vue
<script setup> import { ref } from 'vue' const count = ref(0) </script> <template> <p class="greeting">{{ count }}</p> </template> <style scoped> .counter { color: orangered; } </style>

This format is very convenient for small components, but it can become a bit overwhelming for larger components. In this case, you can split your SFC into multiple files using the src attribute to import an external file for a language block:

Component.vue
<script src="./script.js"></script> <template src="./template.html"></template> <style scoped src="./styles.css"></style>

Warning

This approach doesn't work with the <script setup> block. Compiler macros like defineProps or defineEmits are compiler macros only usable inside <script setup>.

But you can import any JavaScript/Typescript file:

Component.vue
<script setup lang="ts"> defineProps<{ msg: string }>() import { msg } from './script.ts' </script> <template src="./template.html"></template> <style scoped src="./styles.css"></style>

Try it yourself:

Info

I personally never needed and used this feature, but I think it's good to know that it exists.

Instead, I prefer to use Composition API to extract shared logic in a separate file or split the component into multiple components.