Single File Component
A component architecture where template, logic, and styles are co-located in a single file.
Also known as: SFC
Category: Techniques
Tags: frontend, components, architecture, vue, svelte, web-development
Explanation
A Single File Component (SFC) is a component development pattern where all the parts of a UI component - its template (HTML), logic (JavaScript), and styles (CSS) - are contained within a single file. This pattern is popular in modern frontend frameworks.
Structure:
A typical SFC contains three sections:
1. Template: The HTML structure of the component
2. Script: The JavaScript/TypeScript logic
3. Style: The CSS/SCSS styling (often scoped)
Example (Vue.js):
```
<template>
<div class="greeting">{{ message }}</div>
</template>
<script>
export default {
data() {
return { message: 'Hello!' }
}
}
</script>
<style scoped>
.greeting { color: blue; }
</style>
```
Advantages:
- Co-location: Related code stays together, improving maintainability
- Self-contained: Components are portable and reusable
- Clear boundaries: Easy to understand component scope
- Scoped styles: CSS can be isolated to the component
- Developer experience: Tooling can provide better support
Implementations:
- Vue.js: .vue files (most prominent SFC example)
- Svelte: .svelte files
- Angular: Component files with templateUrl and styleUrls
- React: Though not traditional SFC, JSX + CSS-in-JS achieves similar co-location
Considerations:
- Large components may become unwieldy
- Requires build tools to process
- Team preferences vary (some prefer separation)
SFCs represent a shift from traditional separation of concerns (HTML/CSS/JS in separate files) to a component-centric approach.
Related Concepts
← Back to all concepts