Spec Registry
Help your agents use open-source better. Learn more.
Find usage specs for your project’s dependencies
- Author
- tessl
- Last updated
- Spec files
npm-svelte
Describes: npm/svelte
- Description
- Revolutionary JavaScript framework and compiler that builds web applications without runtime overhead by compiling components at build time.
- Author
- tessl
- Last updated
compiler.md docs/
1# Compiler23Complete compilation pipeline for transforming Svelte components into optimized JavaScript with preprocessing support.45## Capabilities67### Component Compilation89Transform Svelte component source code into optimized JavaScript modules.1011```javascript { .api }12/**13* Compiles a Svelte component into JavaScript14* @param source - Svelte component source code15* @param options - Compilation options16* @returns Compilation result with generated code and metadata17*/18function compile(source: string, options?: CompileOptions): CompileResult;1920interface CompileOptions {21/** Component name (inferred from filename if not provided) */22name?: string;23/** Source filename for debugging and sourcemaps */24filename?: string;25/** Generation target: 'dom', 'ssr', or false */26generate?: 'dom' | 'ssr' | false;27/** Error handling mode: 'throw' or 'warn' */28errorMode?: 'throw' | 'warn';29/** Variables report mode: 'strict', 'full', or false */30varsReport?: 'full' | 'strict' | false;31/** Enable sourcemap generation */32enableSourcemap?: boolean | { js: boolean; css: boolean };33/** Development mode with runtime checks */34dev?: boolean;35/** Generate accessors for props */36accessors?: boolean;37/** Treat objects as immutable */38immutable?: boolean;39/** Enable hydration support */40hydratable?: boolean;41/** Generate legacy-compatible code */42legacy?: boolean;43/** Generate custom element constructor */44customElement?: boolean;45/** Custom element tag name */46tag?: string;47/** CSS handling: 'injected', 'external', 'none' */48css?: 'injected' | 'external' | 'none' | boolean;49/** Preserve HTML comments in SSR */50preserveComments?: boolean;51/** Preserve whitespace */52preserveWhitespace?: boolean;53}5455interface CompileResult {56/** Generated JavaScript code */57js: {58code: string;59map: any;60};61/** Generated CSS code */62css: {63code: string;64map: SourceMap;65};66/** Abstract syntax tree */67ast: Ast;68/** Compilation warnings */69warnings: Warning[];70/** Variable declarations */71vars: Var[];72/** Performance statistics */73stats: {74timings: { total: number };75};76}77```7879**Usage Examples:**8081```javascript82import { compile } from "svelte/compiler";8384// Basic compilation85const source = `86<script>87export let name = 'world';88</script>8990<h1>Hello {name}!</h1>91`;9293const result = compile(source, {94filename: 'Hello.svelte',95dev: true96});9798console.log(result.js.code); // Generated JavaScript99console.log(result.css.code); // Generated CSS100console.log(result.warnings); // Any warnings101102// SSR compilation103const ssrResult = compile(source, {104generate: 'ssr',105hydratable: true106});107108// Custom element compilation109const customElementResult = compile(source, {110customElement: true,111tag: 'hello-component'112});113```114115### AST Parsing116117Parse Svelte component templates into abstract syntax trees for analysis and transformation.118119```javascript { .api }120/**121* Parses a Svelte component into an AST without compilation122* @param template - Svelte component source123* @param options - Parser options124* @returns Abstract syntax tree125*/126function parse(template: string, options?: ParserOptions): Ast;127128interface ParserOptions {129/** Source filename */130filename?: string;131/** Parse as custom element */132customElement?: boolean;133/** CSS mode for parsing */134css?: 'injected' | 'external' | 'none' | boolean;135}136137interface Ast {138/** HTML template AST */139html: TemplateNode;140/** CSS style block AST */141css?: Style;142/** Instance script AST */143instance?: Script;144/** Module script AST */145module?: Script;146}147```148149**Usage Examples:**150151```javascript152import { parse } from "svelte/compiler";153154const template = `155<script>156let count = 0;157</script>158159<button on:click={() => count++}>160Count: {count}161</button>162163<style>164button { color: blue; }165</style>166`;167168const ast = parse(template, {169filename: 'Counter.svelte'170});171172console.log(ast.html); // Template nodes173console.log(ast.instance); // Script block174console.log(ast.css); // Style block175```176177### Preprocessing178179Transform component source code before compilation using custom preprocessors.180181```javascript { .api }182/**183* Applies preprocessors to transform component source184* @param source - Original component source185* @param preprocessor - Preprocessor configuration186* @param options - Processing options187* @returns Processed source code188*/189function preprocess(190source: string,191preprocessor: PreprocessorGroup | PreprocessorGroup[],192options?: { filename?: string }193): Promise<Processed>;194195interface PreprocessorGroup {196/** Preprocessor name */197name?: string;198/** Markup preprocessor */199markup?: MarkupPreprocessor;200/** Style preprocessor */201style?: Preprocessor;202/** Script preprocessor */203script?: Preprocessor;204}205206type MarkupPreprocessor = (options: {207content: string;208filename?: string;209}) => Processed | void | Promise<Processed | void>;210211type Preprocessor = (options: {212content: string;213attributes: Record<string, string | boolean>;214markup: string;215filename?: string;216}) => Processed | void | Promise<Processed | void>;217218interface Processed {219/** Transformed code */220code: string;221/** Source map */222map?: string | object;223/** Additional dependencies to watch */224dependencies?: string[];225/** Updated attributes */226attributes?: Record<string, string | boolean>;227}228```229230**Usage Examples:**231232```javascript233import { preprocess } from "svelte/compiler";234235// TypeScript preprocessing236const preprocessors = {237script: ({ content, attributes }) => {238if (attributes.lang === 'ts') {239// Transform TypeScript to JavaScript240return {241code: transformTypeScript(content),242map: generateSourceMap()243};244}245},246style: ({ content, attributes }) => {247if (attributes.lang === 'scss') {248// Transform SCSS to CSS249return {250code: compileSass(content)251};252}253}254};255256const processed = await preprocess(source, preprocessors, {257filename: 'Component.svelte'258});259260console.log(processed.code); // Transformed source261```262263### AST Traversal264265Utility for walking and analyzing AST nodes.266267```javascript { .api }268/**269* Walk an AST with enter/leave callbacks270* @param ast - AST node to traverse271* @param handlers - Enter and leave callback functions272*/273function walk(ast: Node, handlers: {274enter?: (node: Node, parent: Node, prop: string, index: number) => void;275leave?: (node: Node, parent: Node, prop: string, index: number) => void;276}): void;277```278279**Usage Examples:**280281```javascript282import { parse, walk } from "svelte/compiler";283284const ast = parse(template);285286// Find all variable references287const variables = [];288289walk(ast.html, {290enter(node) {291if (node.type === 'Identifier') {292variables.push(node.name);293}294}295});296297console.log('Variables used:', variables);298```299300### Version Information301302```javascript { .api }303/**304* Current Svelte version305*/306const VERSION: string;307```308309## AST Node Types310311```javascript { .api }312interface TemplateNode {313start: number;314end: number;315type: string;316children?: TemplateNode[];317}318319interface Element extends TemplateNode {320type: 'Element' | 'InlineComponent' | 'SlotTemplate' | 'Title' | 'Slot' | 'Head' | 'Options' | 'Window' | 'Document' | 'Body';321name: string;322attributes: Array<Attribute | SpreadAttribute | Directive>;323}324325interface Text extends TemplateNode {326type: 'Text';327data: string;328}329330interface MustacheTag extends TemplateNode {331type: 'MustacheTag' | 'RawMustacheTag';332expression: Node;333}334335interface Script extends TemplateNode {336type: 'Script';337context: string;338content: Program;339}340341interface Style extends TemplateNode {342type: 'Style';343attributes: any[];344children: any[];345content: {346start: number;347end: number;348styles: string;349};350}351352interface Warning {353start?: { line: number; column: number; pos?: number };354end?: { line: number; column: number };355pos?: number;356code: string;357message: string;358filename?: string;359frame?: string;360toString(): string;361}362363interface Var {364name: string;365export_name?: string;366injected?: boolean;367module?: boolean;368mutated?: boolean;369reassigned?: boolean;370referenced?: boolean;371writable?: boolean;372}373```