Complete compilation pipeline for transforming Svelte components into optimized JavaScript with preprocessing support.
Transform Svelte component source code into optimized JavaScript modules.
/**
* Compiles a Svelte component into JavaScript
* @param source - Svelte component source code
* @param options - Compilation options
* @returns Compilation result with generated code and metadata
*/
function compile(source: string, options?: CompileOptions): CompileResult;
interface CompileOptions {
/** Component name (inferred from filename if not provided) */
name?: string;
/** Source filename for debugging and sourcemaps */
filename?: string;
/** Generation target: 'dom', 'ssr', or false */
generate?: 'dom' | 'ssr' | false;
/** Error handling mode: 'throw' or 'warn' */
errorMode?: 'throw' | 'warn';
/** Variables report mode: 'strict', 'full', or false */
varsReport?: 'full' | 'strict' | false;
/** Enable sourcemap generation */
enableSourcemap?: boolean | { js: boolean; css: boolean };
/** Development mode with runtime checks */
dev?: boolean;
/** Generate accessors for props */
accessors?: boolean;
/** Treat objects as immutable */
immutable?: boolean;
/** Enable hydration support */
hydratable?: boolean;
/** Generate legacy-compatible code */
legacy?: boolean;
/** Generate custom element constructor */
customElement?: boolean;
/** Custom element tag name */
tag?: string;
/** CSS handling: 'injected', 'external', 'none' */
css?: 'injected' | 'external' | 'none' | boolean;
/** Preserve HTML comments in SSR */
preserveComments?: boolean;
/** Preserve whitespace */
preserveWhitespace?: boolean;
}
interface CompileResult {
/** Generated JavaScript code */
js: {
code: string;
map: any;
};
/** Generated CSS code */
css: {
code: string;
map: SourceMap;
};
/** Abstract syntax tree */
ast: Ast;
/** Compilation warnings */
warnings: Warning[];
/** Variable declarations */
vars: Var[];
/** Performance statistics */
stats: {
timings: { total: number };
};
}Usage Examples:
import { compile } from "svelte/compiler";
// Basic compilation
const source = `
<script>
export let name = 'world';
</script>
<h1>Hello {name}!</h1>
`;
const result = compile(source, {
filename: 'Hello.svelte',
dev: true
});
console.log(result.js.code); // Generated JavaScript
console.log(result.css.code); // Generated CSS
console.log(result.warnings); // Any warnings
// SSR compilation
const ssrResult = compile(source, {
generate: 'ssr',
hydratable: true
});
// Custom element compilation
const customElementResult = compile(source, {
customElement: true,
tag: 'hello-component'
});Parse Svelte component templates into abstract syntax trees for analysis and transformation.
/**
* Parses a Svelte component into an AST without compilation
* @param template - Svelte component source
* @param options - Parser options
* @returns Abstract syntax tree
*/
function parse(template: string, options?: ParserOptions): Ast;
interface ParserOptions {
/** Source filename */
filename?: string;
/** Parse as custom element */
customElement?: boolean;
/** CSS mode for parsing */
css?: 'injected' | 'external' | 'none' | boolean;
}
interface Ast {
/** HTML template AST */
html: TemplateNode;
/** CSS style block AST */
css?: Style;
/** Instance script AST */
instance?: Script;
/** Module script AST */
module?: Script;
}Usage Examples:
import { parse } from "svelte/compiler";
const template = `
<script>
let count = 0;
</script>
<button on:click={() => count++}>
Count: {count}
</button>
<style>
button { color: blue; }
</style>
`;
const ast = parse(template, {
filename: 'Counter.svelte'
});
console.log(ast.html); // Template nodes
console.log(ast.instance); // Script block
console.log(ast.css); // Style blockTransform component source code before compilation using custom preprocessors.
/**
* Applies preprocessors to transform component source
* @param source - Original component source
* @param preprocessor - Preprocessor configuration
* @param options - Processing options
* @returns Processed source code
*/
function preprocess(
source: string,
preprocessor: PreprocessorGroup | PreprocessorGroup[],
options?: { filename?: string }
): Promise<Processed>;
interface PreprocessorGroup {
/** Preprocessor name */
name?: string;
/** Markup preprocessor */
markup?: MarkupPreprocessor;
/** Style preprocessor */
style?: Preprocessor;
/** Script preprocessor */
script?: Preprocessor;
}
type MarkupPreprocessor = (options: {
content: string;
filename?: string;
}) => Processed | void | Promise<Processed | void>;
type Preprocessor = (options: {
content: string;
attributes: Record<string, string | boolean>;
markup: string;
filename?: string;
}) => Processed | void | Promise<Processed | void>;
interface Processed {
/** Transformed code */
code: string;
/** Source map */
map?: string | object;
/** Additional dependencies to watch */
dependencies?: string[];
/** Updated attributes */
attributes?: Record<string, string | boolean>;
}Usage Examples:
import { preprocess } from "svelte/compiler";
// TypeScript preprocessing
const preprocessors = {
script: ({ content, attributes }) => {
if (attributes.lang === 'ts') {
// Transform TypeScript to JavaScript
return {
code: transformTypeScript(content),
map: generateSourceMap()
};
}
},
style: ({ content, attributes }) => {
if (attributes.lang === 'scss') {
// Transform SCSS to CSS
return {
code: compileSass(content)
};
}
}
};
const processed = await preprocess(source, preprocessors, {
filename: 'Component.svelte'
});
console.log(processed.code); // Transformed sourceUtility for walking and analyzing AST nodes.
/**
* Walk an AST with enter/leave callbacks
* @param ast - AST node to traverse
* @param handlers - Enter and leave callback functions
*/
function walk(ast: Node, handlers: {
enter?: (node: Node, parent: Node, prop: string, index: number) => void;
leave?: (node: Node, parent: Node, prop: string, index: number) => void;
}): void;Usage Examples:
import { parse, walk } from "svelte/compiler";
const ast = parse(template);
// Find all variable references
const variables = [];
walk(ast.html, {
enter(node) {
if (node.type === 'Identifier') {
variables.push(node.name);
}
}
});
console.log('Variables used:', variables);/**
* Current Svelte version
*/
const VERSION: string;interface TemplateNode {
start: number;
end: number;
type: string;
children?: TemplateNode[];
}
interface Element extends TemplateNode {
type: 'Element' | 'InlineComponent' | 'SlotTemplate' | 'Title' | 'Slot' | 'Head' | 'Options' | 'Window' | 'Document' | 'Body';
name: string;
attributes: Array<Attribute | SpreadAttribute | Directive>;
}
interface Text extends TemplateNode {
type: 'Text';
data: string;
}
interface MustacheTag extends TemplateNode {
type: 'MustacheTag' | 'RawMustacheTag';
expression: Node;
}
interface Script extends TemplateNode {
type: 'Script';
context: string;
content: Program;
}
interface Style extends TemplateNode {
type: 'Style';
attributes: any[];
children: any[];
content: {
start: number;
end: number;
styles: string;
};
}
interface Warning {
start?: { line: number; column: number; pos?: number };
end?: { line: number; column: number };
pos?: number;
code: string;
message: string;
filename?: string;
frame?: string;
toString(): string;
}
interface Var {
name: string;
export_name?: string;
injected?: boolean;
module?: boolean;
mutated?: boolean;
reassigned?: boolean;
referenced?: boolean;
writable?: boolean;
}