Core compiler for Vue.js template compilation and transformation
—
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.
The primary entry point for template compilation that orchestrates the entire compilation pipeline.
/**
* Compiles a Vue template into a JavaScript render function
* @param source - Template string or pre-parsed AST
* @param options - Compilation configuration options
* @returns Compilation result with generated code and metadata
*/
function baseCompile(
source: string | RootNode,
options?: CompilerOptions
): CodegenResult;
interface CodegenResult {
/** Generated JavaScript code for the render function */
code: string;
/** Code that should be placed before the render function (imports, helpers) */
preamble: string;
/** The final AST after all transformations */
ast: RootNode;
/** Source map for debugging (when sourceMap option is enabled) */
map?: RawSourceMap;
}Usage Examples:
import { baseCompile } from "@vue/compiler-core";
// Basic template compilation
const result = baseCompile('<div>{{ message }}</div>');
console.log(result.code);
// With options
const result = baseCompile('<div v-if="show">Content</div>', {
mode: 'module',
hoistStatic: true,
prefixIdentifiers: true
});Converts template strings into Abstract Syntax Trees (AST) for further processing.
/**
* Parses a Vue template string into an AST
* @param input - Template string to parse
* @param options - Parser configuration options
* @returns Root AST node representing the entire template
*/
function baseParse(input: string, options?: ParserOptions): RootNode;Usage Examples:
import { baseParse } from "@vue/compiler-core";
// Basic parsing
const ast = baseParse('<div><span>{{ text }}</span></div>');
// Parse with custom delimiters
const ast = baseParse('[[[ message ]]]', {
delimiters: ['[[[', ']]]']
});
// Parse as single file component
const ast = baseParse(template, {
parseMode: 'sfc'
});Applies transformations to AST nodes to handle Vue-specific syntax and optimizations.
/**
* Transforms an AST by applying node and directive transforms
* @param root - Root AST node to transform
* @param options - Transformation configuration and plugins
*/
function transform(root: RootNode, options: TransformOptions): void;
/**
* Creates a transformation context for processing AST nodes
* @param root - Root AST node
* @param options - Transformation options
* @returns Context object containing transformation state and helpers
*/
function createTransformContext(
root: RootNode,
options: TransformOptions
): TransformContext;
/**
* Traverses and transforms a single AST node and its children
* @param node - AST node to traverse
* @param context - Transformation context
*/
function traverseNode(
node: RootNode | TemplateChildNode,
context: TransformContext
): void;Usage Examples:
import { baseParse, transform, getBaseTransformPreset } from "@vue/compiler-core";
const ast = baseParse('<div v-if="show">{{ message }}</div>');
const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
transform(ast, {
nodeTransforms,
directiveTransforms,
hoistStatic: true
});Converts transformed AST into executable JavaScript code.
/**
* Generates JavaScript code from a transformed AST
* @param ast - Root AST node after transformations
* @param options - Code generation options
* @returns Generated code result with source map support
*/
function generate(
ast: RootNode,
options?: CodegenOptions & {
onContextCreated?: (context: CodegenContext) => void;
}
): CodegenResult;
interface CodegenContext {
/** Current generated code string */
code: string;
/** Current indentation level */
level: number;
/** Whether currently inside a push statement */
inVOnceWrapper: boolean;
/** Map of helper names to usage count */
helper(key: symbol): string;
/** Add code to output */
push(code: string, node?: CodegenNode): void;
/** Increase indentation level */
indent(): void;
/** Decrease indentation level */
deindent(withinNewline?: boolean): void;
/** Add newline with proper indentation */
newline(): void;
}Usage Examples:
import { generate } from "@vue/compiler-core";
// Generate code with options
const result = generate(transformedAst, {
mode: 'module',
sourceMap: true,
optimizeImports: true
});
// Generate function mode code
const result = generate(transformedAst, {
mode: 'function',
runtimeGlobalName: 'Vue'
});Pre-configured sets of transforms for common compilation scenarios.
/**
* Returns the base set of node transforms and directive transforms
* @param prefixIdentifiers - Whether to prefix identifiers for scoping
* @returns Tuple of node transforms and directive transform map
*/
function getBaseTransformPreset(prefixIdentifiers?: boolean): TransformPreset;
type TransformPreset = [
NodeTransform[],
Record<string, DirectiveTransform>
];Usage Examples:
import { getBaseTransformPreset } from "@vue/compiler-core";
// Get standard transforms
const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
// Get transforms with identifier prefixing (for non-browser environments)
const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(true);
// Use in transformation
transform(ast, {
nodeTransforms,
directiveTransforms
});Complete configuration interface combining all compilation phases.
interface CompilerOptions extends ParserOptions, TransformOptions, CodegenOptions {
// Inherits all options from parser, transform, and codegen phases
}Configuration for the template parsing phase.
interface ParserOptions {
/** Parsing mode: base HTML, full HTML, or SFC template */
parseMode?: 'base' | 'html' | 'sfc';
/** Default namespace for elements */
ns?: Namespaces;
/** Template interpolation delimiters */
delimiters?: [string, string];
/** Custom namespace resolution */
getNamespace?: (tag: string, parent: ElementNode | undefined, rootNamespace: Namespace) => Namespace;
/** Check if tag is a native HTML tag */
isNativeTag?: (tag: string) => boolean;
/** Check if tag is a void element (self-closing) */
isVoidTag?: (tag: string) => boolean;
/** Check if tag preserves whitespace */
isPreTag?: (tag: string) => boolean;
/** Check if tag ignores newlines after opening */
isIgnoreNewlineTag?: (tag: string) => boolean;
/** Resolve built-in Vue components */
isBuiltInComponent?: (tag: string) => symbol | void;
/** Check if tag is a custom element */
isCustomElement?: (tag: string) => boolean | void;
/** Custom HTML entity decoder */
decodeEntities?: (rawText: string, asAttr: boolean) => string;
/** Whitespace handling strategy */
whitespace?: 'preserve' | 'condense';
/** Include comment nodes in AST */
comments?: boolean;
/** Prefix identifiers for scoping */
prefixIdentifiers?: boolean;
/** Babel parser plugins for expressions */
expressionPlugins?: ParserPlugin[];
}Configuration for the AST transformation phase.
interface TransformOptions {
/** Array of node transform functions */
nodeTransforms?: NodeTransform[];
/** Map of directive names to transform functions */
directiveTransforms?: Record<string, DirectiveTransform | undefined>;
/** Transform for hoisting static content */
transformHoist?: HoistTransform | null;
/** Resolve built-in Vue components */
isBuiltInComponent?: (tag: string) => symbol | void;
/** Check if tag is a custom element */
isCustomElement?: (tag: string) => boolean | void;
/** Prefix identifiers for scoping */
prefixIdentifiers?: boolean;
/** Enable static hoisting optimization */
hoistStatic?: boolean;
/** Cache inline event handlers */
cacheHandlers?: boolean;
/** Babel parser plugins for expressions */
expressionPlugins?: ParserPlugin[];
/** Component scope ID for scoped CSS */
scopeId?: string | null;
/** Generate code for slotted components */
slotted?: boolean;
/** CSS variables for SSR */
ssrCssVars?: string;
/** Enable HMR (Hot Module Replacement) support */
hmr?: boolean;
/** Generate code for server-side rendering */
ssr?: boolean;
/** Currently in SSR context */
inSSR?: boolean;
/** Binding metadata from script setup */
bindingMetadata?: BindingMetadata;
/** Generate inline component (function mode) */
inline?: boolean;
/** Source is TypeScript */
isTS?: boolean;
/** Source filename for error reporting */
filename?: string;
}Configuration for the JavaScript code generation phase.
interface CodegenOptions {
/** Output format: ES module or function */
mode?: 'module' | 'function';
/** Generate source maps */
sourceMap?: boolean;
/** Component scope ID for scoped CSS */
scopeId?: string | null;
/** Optimize import statements */
optimizeImports?: boolean;
/** Runtime helper module name */
runtimeModuleName?: string;
/** SSR runtime helper module name */
ssrRuntimeModuleName?: string;
/** Global runtime name (function mode) */
runtimeGlobalName?: string;
}Information about variable bindings in template scope.
type BindingMetadata = {
[key: string]: BindingTypes | undefined;
} & {
__isScriptSetup?: boolean;
__propsAliases?: Record<string, string>;
};
enum BindingTypes {
DATA = 'data',
PROPS = 'props',
PROPS_ALIASED = 'props-aliased',
SETUP_LET = 'setup-let',
SETUP_CONST = 'setup-const',
SETUP_REACTIVE_CONST = 'setup-reactive-const',
SETUP_MAYBE_REF = 'setup-maybe-ref',
SETUP_REF = 'setup-ref',
OPTIONS = 'options',
LITERAL_CONST = 'literal-const'
}Function signatures for transformation system.
type HoistTransform = (
children: TemplateChildNode[],
context: TransformContext,
parent: ParentNode
) => void;
type NodeTransform = (
node: RootNode | TemplateChildNode,
context: TransformContext
) => void | (() => void) | (() => void)[];
type DirectiveTransform = (
dir: DirectiveNode,
node: ElementNode,
context: TransformContext,
augmentor?: (ret: DirectiveTransformResult) => DirectiveTransformResult
) => DirectiveTransformResult;Install with Tessl CLI
npx tessl i tessl/npm-vue--compiler-core