0
# Compilation Pipeline
1
2
The Vue compiler core provides a complete template compilation pipeline that transforms Vue template syntax into optimized JavaScript render functions. The compilation process consists of three main phases: parsing, transformation, and code generation.
3
4
## Capabilities
5
6
### Main Compilation Function
7
8
The primary entry point for template compilation that orchestrates the entire compilation pipeline.
9
10
```typescript { .api }
11
/**
12
* Compiles a Vue template into a JavaScript render function
13
* @param source - Template string or pre-parsed AST
14
* @param options - Compilation configuration options
15
* @returns Compilation result with generated code and metadata
16
*/
17
function baseCompile(
18
source: string | RootNode,
19
options?: CompilerOptions
20
): CodegenResult;
21
22
interface CodegenResult {
23
/** Generated JavaScript code for the render function */
24
code: string;
25
/** Code that should be placed before the render function (imports, helpers) */
26
preamble: string;
27
/** The final AST after all transformations */
28
ast: RootNode;
29
/** Source map for debugging (when sourceMap option is enabled) */
30
map?: RawSourceMap;
31
}
32
```
33
34
**Usage Examples:**
35
36
```typescript
37
import { baseCompile } from "@vue/compiler-core";
38
39
// Basic template compilation
40
const result = baseCompile('<div>{{ message }}</div>');
41
console.log(result.code);
42
43
// With options
44
const result = baseCompile('<div v-if="show">Content</div>', {
45
mode: 'module',
46
hoistStatic: true,
47
prefixIdentifiers: true
48
});
49
```
50
51
### Template Parsing
52
53
Converts template strings into Abstract Syntax Trees (AST) for further processing.
54
55
```typescript { .api }
56
/**
57
* Parses a Vue template string into an AST
58
* @param input - Template string to parse
59
* @param options - Parser configuration options
60
* @returns Root AST node representing the entire template
61
*/
62
function baseParse(input: string, options?: ParserOptions): RootNode;
63
```
64
65
**Usage Examples:**
66
67
```typescript
68
import { baseParse } from "@vue/compiler-core";
69
70
// Basic parsing
71
const ast = baseParse('<div><span>{{ text }}</span></div>');
72
73
// Parse with custom delimiters
74
const ast = baseParse('[[[ message ]]]', {
75
delimiters: ['[[[', ']]]']
76
});
77
78
// Parse as single file component
79
const ast = baseParse(template, {
80
parseMode: 'sfc'
81
});
82
```
83
84
### AST Transformation
85
86
Applies transformations to AST nodes to handle Vue-specific syntax and optimizations.
87
88
```typescript { .api }
89
/**
90
* Transforms an AST by applying node and directive transforms
91
* @param root - Root AST node to transform
92
* @param options - Transformation configuration and plugins
93
*/
94
function transform(root: RootNode, options: TransformOptions): void;
95
96
/**
97
* Creates a transformation context for processing AST nodes
98
* @param root - Root AST node
99
* @param options - Transformation options
100
* @returns Context object containing transformation state and helpers
101
*/
102
function createTransformContext(
103
root: RootNode,
104
options: TransformOptions
105
): TransformContext;
106
107
/**
108
* Traverses and transforms a single AST node and its children
109
* @param node - AST node to traverse
110
* @param context - Transformation context
111
*/
112
function traverseNode(
113
node: RootNode | TemplateChildNode,
114
context: TransformContext
115
): void;
116
```
117
118
**Usage Examples:**
119
120
```typescript
121
import { baseParse, transform, getBaseTransformPreset } from "@vue/compiler-core";
122
123
const ast = baseParse('<div v-if="show">{{ message }}</div>');
124
const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
125
126
transform(ast, {
127
nodeTransforms,
128
directiveTransforms,
129
hoistStatic: true
130
});
131
```
132
133
### Code Generation
134
135
Converts transformed AST into executable JavaScript code.
136
137
```typescript { .api }
138
/**
139
* Generates JavaScript code from a transformed AST
140
* @param ast - Root AST node after transformations
141
* @param options - Code generation options
142
* @returns Generated code result with source map support
143
*/
144
function generate(
145
ast: RootNode,
146
options?: CodegenOptions & {
147
onContextCreated?: (context: CodegenContext) => void;
148
}
149
): CodegenResult;
150
151
interface CodegenContext {
152
/** Current generated code string */
153
code: string;
154
/** Current indentation level */
155
level: number;
156
/** Whether currently inside a push statement */
157
inVOnceWrapper: boolean;
158
/** Map of helper names to usage count */
159
helper(key: symbol): string;
160
/** Add code to output */
161
push(code: string, node?: CodegenNode): void;
162
/** Increase indentation level */
163
indent(): void;
164
/** Decrease indentation level */
165
deindent(withinNewline?: boolean): void;
166
/** Add newline with proper indentation */
167
newline(): void;
168
}
169
```
170
171
**Usage Examples:**
172
173
```typescript
174
import { generate } from "@vue/compiler-core";
175
176
// Generate code with options
177
const result = generate(transformedAst, {
178
mode: 'module',
179
sourceMap: true,
180
optimizeImports: true
181
});
182
183
// Generate function mode code
184
const result = generate(transformedAst, {
185
mode: 'function',
186
runtimeGlobalName: 'Vue'
187
});
188
```
189
190
### Transform Presets
191
192
Pre-configured sets of transforms for common compilation scenarios.
193
194
```typescript { .api }
195
/**
196
* Returns the base set of node transforms and directive transforms
197
* @param prefixIdentifiers - Whether to prefix identifiers for scoping
198
* @returns Tuple of node transforms and directive transform map
199
*/
200
function getBaseTransformPreset(prefixIdentifiers?: boolean): TransformPreset;
201
202
type TransformPreset = [
203
NodeTransform[],
204
Record<string, DirectiveTransform>
205
];
206
```
207
208
**Usage Examples:**
209
210
```typescript
211
import { getBaseTransformPreset } from "@vue/compiler-core";
212
213
// Get standard transforms
214
const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
215
216
// Get transforms with identifier prefixing (for non-browser environments)
217
const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(true);
218
219
// Use in transformation
220
transform(ast, {
221
nodeTransforms,
222
directiveTransforms
223
});
224
```
225
226
## Configuration Options
227
228
### Compiler Options
229
230
Complete configuration interface combining all compilation phases.
231
232
```typescript { .api }
233
interface CompilerOptions extends ParserOptions, TransformOptions, CodegenOptions {
234
// Inherits all options from parser, transform, and codegen phases
235
}
236
```
237
238
### Parser Options
239
240
Configuration for the template parsing phase.
241
242
```typescript { .api }
243
interface ParserOptions {
244
/** Parsing mode: base HTML, full HTML, or SFC template */
245
parseMode?: 'base' | 'html' | 'sfc';
246
/** Default namespace for elements */
247
ns?: Namespaces;
248
/** Template interpolation delimiters */
249
delimiters?: [string, string];
250
/** Custom namespace resolution */
251
getNamespace?: (tag: string, parent: ElementNode | undefined, rootNamespace: Namespace) => Namespace;
252
/** Check if tag is a native HTML tag */
253
isNativeTag?: (tag: string) => boolean;
254
/** Check if tag is a void element (self-closing) */
255
isVoidTag?: (tag: string) => boolean;
256
/** Check if tag preserves whitespace */
257
isPreTag?: (tag: string) => boolean;
258
/** Check if tag ignores newlines after opening */
259
isIgnoreNewlineTag?: (tag: string) => boolean;
260
/** Resolve built-in Vue components */
261
isBuiltInComponent?: (tag: string) => symbol | void;
262
/** Check if tag is a custom element */
263
isCustomElement?: (tag: string) => boolean | void;
264
/** Custom HTML entity decoder */
265
decodeEntities?: (rawText: string, asAttr: boolean) => string;
266
/** Whitespace handling strategy */
267
whitespace?: 'preserve' | 'condense';
268
/** Include comment nodes in AST */
269
comments?: boolean;
270
/** Prefix identifiers for scoping */
271
prefixIdentifiers?: boolean;
272
/** Babel parser plugins for expressions */
273
expressionPlugins?: ParserPlugin[];
274
}
275
```
276
277
### Transform Options
278
279
Configuration for the AST transformation phase.
280
281
```typescript { .api }
282
interface TransformOptions {
283
/** Array of node transform functions */
284
nodeTransforms?: NodeTransform[];
285
/** Map of directive names to transform functions */
286
directiveTransforms?: Record<string, DirectiveTransform | undefined>;
287
/** Transform for hoisting static content */
288
transformHoist?: HoistTransform | null;
289
/** Resolve built-in Vue components */
290
isBuiltInComponent?: (tag: string) => symbol | void;
291
/** Check if tag is a custom element */
292
isCustomElement?: (tag: string) => boolean | void;
293
/** Prefix identifiers for scoping */
294
prefixIdentifiers?: boolean;
295
/** Enable static hoisting optimization */
296
hoistStatic?: boolean;
297
/** Cache inline event handlers */
298
cacheHandlers?: boolean;
299
/** Babel parser plugins for expressions */
300
expressionPlugins?: ParserPlugin[];
301
/** Component scope ID for scoped CSS */
302
scopeId?: string | null;
303
/** Generate code for slotted components */
304
slotted?: boolean;
305
/** CSS variables for SSR */
306
ssrCssVars?: string;
307
/** Enable HMR (Hot Module Replacement) support */
308
hmr?: boolean;
309
/** Generate code for server-side rendering */
310
ssr?: boolean;
311
/** Currently in SSR context */
312
inSSR?: boolean;
313
/** Binding metadata from script setup */
314
bindingMetadata?: BindingMetadata;
315
/** Generate inline component (function mode) */
316
inline?: boolean;
317
/** Source is TypeScript */
318
isTS?: boolean;
319
/** Source filename for error reporting */
320
filename?: string;
321
}
322
```
323
324
### Code Generation Options
325
326
Configuration for the JavaScript code generation phase.
327
328
```typescript { .api }
329
interface CodegenOptions {
330
/** Output format: ES module or function */
331
mode?: 'module' | 'function';
332
/** Generate source maps */
333
sourceMap?: boolean;
334
/** Component scope ID for scoped CSS */
335
scopeId?: string | null;
336
/** Optimize import statements */
337
optimizeImports?: boolean;
338
/** Runtime helper module name */
339
runtimeModuleName?: string;
340
/** SSR runtime helper module name */
341
ssrRuntimeModuleName?: string;
342
/** Global runtime name (function mode) */
343
runtimeGlobalName?: string;
344
}
345
```
346
347
## Supporting Types
348
349
### Binding Metadata
350
351
Information about variable bindings in template scope.
352
353
```typescript { .api }
354
type BindingMetadata = {
355
[key: string]: BindingTypes | undefined;
356
} & {
357
__isScriptSetup?: boolean;
358
__propsAliases?: Record<string, string>;
359
};
360
361
enum BindingTypes {
362
DATA = 'data',
363
PROPS = 'props',
364
PROPS_ALIASED = 'props-aliased',
365
SETUP_LET = 'setup-let',
366
SETUP_CONST = 'setup-const',
367
SETUP_REACTIVE_CONST = 'setup-reactive-const',
368
SETUP_MAYBE_REF = 'setup-maybe-ref',
369
SETUP_REF = 'setup-ref',
370
OPTIONS = 'options',
371
LITERAL_CONST = 'literal-const'
372
}
373
```
374
375
### Transform Function Types
376
377
Function signatures for transformation system.
378
379
```typescript { .api }
380
type HoistTransform = (
381
children: TemplateChildNode[],
382
context: TransformContext,
383
parent: ParentNode
384
) => void;
385
386
type NodeTransform = (
387
node: RootNode | TemplateChildNode,
388
context: TransformContext
389
) => void | (() => void) | (() => void)[];
390
391
type DirectiveTransform = (
392
dir: DirectiveNode,
393
node: ElementNode,
394
context: TransformContext,
395
augmentor?: (ret: DirectiveTransformResult) => DirectiveTransformResult
396
) => DirectiveTransformResult;
397
```