What is @vue/compiler-sfc?
The @vue/compiler-sfc package is designed for pre-compiling Vue Single File Components (SFCs). It provides parsing and compiling functionalities for Vue components, allowing developers to compile template syntax to render functions, extract custom blocks, and handle scoped CSS, among other things.
What are @vue/compiler-sfc's main functionalities?
Parsing Single File Components
This feature allows you to parse Vue SFCs into an object descriptor that contains the structure of the component, including its template, script, and styles.
const { parse } = require('@vue/compiler-sfc');
const { descriptor } = parse('<template><div>Hello World</div></template>');
Compiling Template to Render Function
This feature compiles the template part of a Vue SFC into a JavaScript render function, which can be used by Vue to render the component.
const { compileTemplate } = require('@vue/compiler-sfc');
const { code } = compileTemplate({ source: '<div>{{ message }}</div>', filename: 'example.vue' });
Handling Scoped CSS
This feature processes the style part of a Vue SFC, adding scoping attributes to the styles to ensure they only apply to the current component.
const { compileStyle } = require('@vue/compiler-sfc');
const { code } = compileStyle({ source: '.example { color: red; }', filename: 'example.vue', scoped: true });
Extracting Custom Blocks
This feature allows you to extract custom blocks from a Vue SFC, which can be used for documentation, testing, or other purposes.
const { parse } = require('@vue/compiler-sfc');
const { descriptor } = parse('<custom-block>Some content</custom-block>');
const customBlockContent = descriptor.customBlocks[0].content;
Other packages similar to @vue/compiler-sfc
vue-template-compiler
This package is similar to @vue/compiler-sfc but is specific to Vue 2. It compiles Vue 2 templates into render functions but does not handle Vue 3's composition API or the newer SFC syntax.
svelte
Svelte is a compiler for Svelte components, which are similar to Vue SFCs. It compiles Svelte components into efficient JavaScript at build time, but it is for a different framework and has a different syntax and API.
react-scripts
Part of the Create React App setup, react-scripts includes functionality to compile React components, including JSX transformation. While it serves a similar purpose for React as @vue/compiler-sfc does for Vue, it is tailored to the React ecosystem.
@vue/compiler-sfc
Lower level utilities for compiling Vue single file components
This package contains lower level utilities that you can use if you are writing a plugin / transform for a bundler or module system that compiles Vue single file components into JavaScript. It is used in vue-loader.
The API surface is intentionally minimal - the goal is to reuse as much as possible while being as flexible as possible.
Browser Build Usage
This package relies on postcss
, postcss-selector-parser
and postcss-modules
API
TODO