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
- A cybernetically enhanced web application framework that compiles to highly optimized JavaScript with reactive state management and component-based architecture.
- Author
- tessl
- Last updated
compiler.md docs/
1# Compiler API23Svelte's compiler API provides functions for compiling Svelte components, parsing source code, preprocessing, and migrating between versions. These tools are essential for build systems, development tools, and code transformation.45## Capabilities67### compile89Converts Svelte component source code into a JavaScript module that exports a component.1011```typescript { .api }12/**13* Compile a Svelte component to JavaScript14* @param source - The component source code15* @param options - Compilation options16* @returns Compilation result with JavaScript and CSS17*/18function compile(source: string, options: CompileOptions): CompileResult;19```2021**Usage Examples:**2223```typescript24import { compile } from "svelte/compiler";2526const source = `27<script>28let count = 0;29</script>3031<button on:click={() => count++}>32Count: {count}33</button>34`;3536// Basic compilation37const result = compile(source, {38filename: "Counter.svelte",39generate: "dom" // or "ssr" for server-side rendering40});4142console.log(result.js.code); // Generated JavaScript43console.log(result.css?.code); // Generated CSS (if any)4445// Advanced compilation options46const advancedResult = compile(source, {47filename: "Counter.svelte",48generate: "dom",49dev: true, // Development mode with runtime checks50css: "external", // Extract CSS to separate file51runes: true, // Enable runes mode52customElement: false,53namespace: "html",54accessors: false,55immutable: false,56preserveComments: false,57preserveWhitespace: false,58sourcemap: true59});60```6162### compileModule6364Compiles JavaScript source code containing runes into a JavaScript module.6566```typescript { .api }67/**68* Compile JavaScript module with runes to optimized JavaScript69* @param source - JavaScript source code with runes70* @param options - Module compilation options71* @returns Compilation result72*/73function compileModule(source: string, options: ModuleCompileOptions): CompileResult;74```7576**Usage Examples:**7778```typescript79import { compileModule } from "svelte/compiler";8081const runesSource = `82let count = $state(0);83let doubled = $derived(count * 2);8485$effect(() => {86console.log('Count changed:', count);87});8889export { count, doubled };90`;9192const result = compileModule(runesSource, {93filename: "store.runes.js",94dev: false,95generate: "client"96});9798console.log(result.js.code); // Compiled JavaScript with optimized reactivity99```100101### parse102103Parses a Svelte component and returns its Abstract Syntax Tree (AST).104105```typescript { .api }106/**107* Parse a Svelte component and return its AST108* @param source - Component source code109* @param options - Parse options110* @returns AST representation of the component111*/112function parse(source: string, options?: {113filename?: string;114modern?: boolean;115loose?: boolean;116}): AST.Root;117```118119**Usage Examples:**120121```typescript122import { parse } from "svelte/compiler";123124const source = `125<script>126export let name = 'world';127</script>128129<h1>Hello {name}!</h1>130131<style>132h1 {133color: purple;134}135</style>136`;137138// Parse with modern AST (recommended)139const ast = parse(source, {140filename: "Hello.svelte",141modern: true142});143144console.log(ast.type); // "Root"145console.log(ast.instance); // Script AST146console.log(ast.fragment); // Template AST147console.log(ast.css); // Style AST148149// Traverse AST150function walkAST(node, callback) {151callback(node);152if (node.children) {153node.children.forEach(child => walkAST(child, callback));154}155}156157walkAST(ast, (node) => {158if (node.type === 'Text') {159console.log('Text node:', node.data);160}161});162```163164### preprocess165166Transforms Svelte component source code using preprocessors before compilation.167168```typescript { .api }169/**170* Transform component source code using preprocessors171* @param source - Component source code172* @param preprocessor - Single preprocessor or array of preprocessors173* @param options - Preprocessing options174* @returns Promise with processed code175*/176function preprocess(177source: string,178preprocessor: PreprocessorGroup | PreprocessorGroup[],179options?: { filename?: string }180): Promise<Processed>;181```182183**Usage Examples:**184185```typescript186import { preprocess } from "svelte/compiler";187188const source = `189<script lang="ts">190let count: number = 0;191</script>192193<style lang="scss">194$primary-color: #ff3e00;195196.button {197background: $primary-color;198&:hover {199opacity: 0.8;200}201}202</style>203204<button class="button" on:click={() => count++}>205Count: {count}206</button>207`;208209// TypeScript and SCSS preprocessing210const result = await preprocess(source, [211{212name: "typescript",213script: ({ content, attributes }) => {214if (attributes.lang === "ts") {215// Transform TypeScript to JavaScript216return {217code: transformTypeScript(content),218map: sourceMap219};220}221}222},223{224name: "scss",225style: ({ content, attributes }) => {226if (attributes.lang === "scss") {227return {228code: compileSCSS(content),229map: sourceMap230};231}232}233}234], {235filename: "Component.svelte"236});237238console.log(result.code); // Processed source ready for compilation239```240241### migrate242243Migrates Svelte 4 code to Svelte 5 syntax, converting to runes and modern patterns.244245```typescript { .api }246/**247* Migrate Svelte 4 code to Svelte 5 runes syntax248* @param source - Svelte 4 source code249* @param options - Migration options250* @returns Migrated code251*/252function migrate(source: string, options?: {253filename?: string;254use_ts?: boolean;255}): { code: string };256```257258**Usage Examples:**259260```typescript261import { migrate } from "svelte/compiler";262263const svelte4Source = `264<script>265export let name = 'world';266let count = 0;267268$: doubled = count * 2;269$: if (count > 5) {270console.log('Count is high!');271}272273import { onMount } from 'svelte';274275onMount(() => {276console.log('Component mounted');277});278</script>279280<h1>Hello {name}!</h1>281<button on:click={() => count++}>282Count: {count}, Doubled: {doubled}283</button>284`;285286// Migrate to Svelte 5287const migrated = migrate(svelte4Source, {288filename: "Component.svelte",289use_ts: false290});291292console.log(migrated.code);293// Output will use $state, $derived, $effect, etc.294```295296### VERSION297298Current version of the Svelte compiler.299300```typescript { .api }301/**302* The current Svelte version string303*/304const VERSION: string;305```306307**Usage Examples:**308309```typescript310import { VERSION } from "svelte/compiler";311312console.log(`Using Svelte compiler version: ${VERSION}`);313314// Conditional logic based on version315const majorVersion = parseInt(VERSION.split('.')[0]);316if (majorVersion >= 5) {317// Use Svelte 5 features318}319```320321## Types322323```typescript { .api }324interface CompileOptions extends ModuleCompileOptions {325/** Component name (inferred from filename if not provided) */326name?: string;327/** Generate custom element instead of regular component */328customElement?: boolean;329/** Create accessors for component props */330accessors?: boolean;331/** Element namespace (html, svg, mathml) */332namespace?: 'html' | 'svg' | 'mathml';333/** Enable immutable mode optimizations */334immutable?: boolean;335/** CSS handling strategy */336css?: 'injected' | 'external';337/** Custom CSS class name hasher */338cssHash?: (args: { name: string; filename: string; css: string; hash: (input: string) => string }) => string;339/** Preserve HTML comments in output */340preserveComments?: boolean;341/** Preserve whitespace in templates */342preserveWhitespace?: boolean;343/** Force runes mode on/off */344runes?: boolean;345/** Expose version in browser globals */346discloseVersion?: boolean;347/** Legacy compatibility options */348compatibility?: { componentApi?: 4 | 5 };349/** Input sourcemap */350sourcemap?: object | string;351/** Output filename for JS sourcemap */352outputFilename?: string;353/** Output filename for CSS sourcemap */354cssOutputFilename?: string;355/** Enable hot module reloading */356hmr?: boolean;357/** Use modern AST format */358modernAst?: boolean;359}360361interface ModuleCompileOptions {362/** Enable development mode with runtime checks */363dev?: boolean;364/** Target platform (client, server, or false for syntax-only) */365generate?: 'client' | 'server' | false;366/** Source filename for debugging */367filename?: string;368/** Root directory for relative paths */369rootDir?: string;370/** Function to filter warnings */371warningFilter?: (warning: Warning) => boolean;372}373374interface CompileResult {375/** Generated JavaScript */376js: {377code: string;378map: SourceMap;379};380/** Generated CSS (null if no styles) */381css: null | {382code: string;383map: SourceMap;384hasGlobal: boolean;385};386/** Compilation warnings */387warnings: Warning[];388/** Compilation metadata */389metadata: {390runes: boolean;391};392/** Component AST */393ast: any;394}395396interface Processed {397/** Transformed source code */398code: string;399/** Source map */400map?: string | object;401/** Additional files to watch */402dependencies?: string[];403/** Updated tag attributes */404attributes?: Record<string, string | boolean>;405}406407interface PreprocessorGroup {408/** Preprocessor name */409name?: string;410/** Markup preprocessor */411markup?: MarkupPreprocessor;412/** Style preprocessor */413style?: Preprocessor;414/** Script preprocessor */415script?: Preprocessor;416}417418type MarkupPreprocessor = (options: {419content: string;420filename?: string;421}) => Processed | void | Promise<Processed | void>;422423type Preprocessor = (options: {424content: string;425attributes: Record<string, string | boolean>;426markup: string;427filename?: string;428}) => Processed | void | Promise<Processed | void>;429```430431## Best Practices4324331. **Use appropriate targets**: Choose 'client' for browser code, 'server' for SSR4342. **Enable dev mode in development**: Provides better error messages and debugging4353. **Extract CSS in production**: Use `css: 'external'` for better caching4364. **Handle warnings**: Implement `warningFilter` to manage compilation warnings4375. **Preserve source maps**: Enable sourcemaps for better debugging experience4386. **Use preprocessing**: Leverage preprocessors for TypeScript, SCSS, PostCSS, etc.