Single-File Components
Vue Single-File Components (SFCs) provide a modular and maintainable way to structure Vue applications. Each.vue file encapsulates the template, script, and styles for a component in a single file.
What are Single-File Components?
A Single-File Component consists of three main sections:The Compiler SFC Package
Vue’s@vue/compiler-sfc package (version 3.5.29) provides low-level utilities for compiling Single-File Components into JavaScript. As of Vue 3.2.13+, this package is included as a dependency of the main vue package and can be accessed as vue/compiler-sfc.
Core API
The compiler-sfc package exports several key functions:parse()
Parses a .vue file into a descriptor object containing the template, script, and style blocks.
compileScript()
Compiles the <script> or <script setup> block, handling features like:
<script setup>syntax- CSS variable injection
- TypeScript support
compileTemplate()
Compiles the raw template into a render function.
compileStyle()
Compiles CSS to handle:
<style scoped>scoping<style module>CSS modules- CSS variable injection
- Preprocessors (via external loaders)
SFC Compilation Workflow
The compilation process follows a facade module pattern:Facade Module
The facade module imports individual blocks of the component:Advanced Features
Parse Cache
The package includes a parse cache to improve performance for repeated parsing:Type Resolution
For TypeScript support, the package provides type resolution utilities:Utilities
The package also exports useful utilities:rewriteDefault()- Rewrites default exportsMagicString- String manipulation utilitybabelParse()- Babel parser for JavaScript/TypeScriptwalk()- AST walker from estree-walkergenerateCodeFrame()- Generate code frames for error messages
Integration with Build Tools
SFC compilation is typically integrated into build tools:- Vite: @vitejs/plugin-vue
- webpack: vue-loader
- Hot Module Replacement (HMR)
- Preprocessor integration
- Parallel compilation
- Source maps
Script Setup
The<script setup> syntax provides a more concise way to write composition API:
compileScript() function handles the transformation of this syntax.