Spec RegistrySpec Registry

Help your agents use open-source better. Learn more.

Find usage specs for your project’s dependencies

>

npm-svelte

Describes: npmnpm/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

How to use

npx @tessl/cli registry install tessl/npm-svelte@5.38.0

compiler.md docs/

1
# Compiler API
2
3
Svelte'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.
4
5
## Capabilities
6
7
### compile
8
9
Converts Svelte component source code into a JavaScript module that exports a component.
10
11
```typescript { .api }
12
/**
13
* Compile a Svelte component to JavaScript
14
* @param source - The component source code
15
* @param options - Compilation options
16
* @returns Compilation result with JavaScript and CSS
17
*/
18
function compile(source: string, options: CompileOptions): CompileResult;
19
```
20
21
**Usage Examples:**
22
23
```typescript
24
import { compile } from "svelte/compiler";
25
26
const source = `
27
<script>
28
let count = 0;
29
</script>
30
31
<button on:click={() => count++}>
32
Count: {count}
33
</button>
34
`;
35
36
// Basic compilation
37
const result = compile(source, {
38
filename: "Counter.svelte",
39
generate: "dom" // or "ssr" for server-side rendering
40
});
41
42
console.log(result.js.code); // Generated JavaScript
43
console.log(result.css?.code); // Generated CSS (if any)
44
45
// Advanced compilation options
46
const advancedResult = compile(source, {
47
filename: "Counter.svelte",
48
generate: "dom",
49
dev: true, // Development mode with runtime checks
50
css: "external", // Extract CSS to separate file
51
runes: true, // Enable runes mode
52
customElement: false,
53
namespace: "html",
54
accessors: false,
55
immutable: false,
56
preserveComments: false,
57
preserveWhitespace: false,
58
sourcemap: true
59
});
60
```
61
62
### compileModule
63
64
Compiles JavaScript source code containing runes into a JavaScript module.
65
66
```typescript { .api }
67
/**
68
* Compile JavaScript module with runes to optimized JavaScript
69
* @param source - JavaScript source code with runes
70
* @param options - Module compilation options
71
* @returns Compilation result
72
*/
73
function compileModule(source: string, options: ModuleCompileOptions): CompileResult;
74
```
75
76
**Usage Examples:**
77
78
```typescript
79
import { compileModule } from "svelte/compiler";
80
81
const runesSource = `
82
let count = $state(0);
83
let doubled = $derived(count * 2);
84
85
$effect(() => {
86
console.log('Count changed:', count);
87
});
88
89
export { count, doubled };
90
`;
91
92
const result = compileModule(runesSource, {
93
filename: "store.runes.js",
94
dev: false,
95
generate: "client"
96
});
97
98
console.log(result.js.code); // Compiled JavaScript with optimized reactivity
99
```
100
101
### parse
102
103
Parses a Svelte component and returns its Abstract Syntax Tree (AST).
104
105
```typescript { .api }
106
/**
107
* Parse a Svelte component and return its AST
108
* @param source - Component source code
109
* @param options - Parse options
110
* @returns AST representation of the component
111
*/
112
function parse(source: string, options?: {
113
filename?: string;
114
modern?: boolean;
115
loose?: boolean;
116
}): AST.Root;
117
```
118
119
**Usage Examples:**
120
121
```typescript
122
import { parse } from "svelte/compiler";
123
124
const source = `
125
<script>
126
export let name = 'world';
127
</script>
128
129
<h1>Hello {name}!</h1>
130
131
<style>
132
h1 {
133
color: purple;
134
}
135
</style>
136
`;
137
138
// Parse with modern AST (recommended)
139
const ast = parse(source, {
140
filename: "Hello.svelte",
141
modern: true
142
});
143
144
console.log(ast.type); // "Root"
145
console.log(ast.instance); // Script AST
146
console.log(ast.fragment); // Template AST
147
console.log(ast.css); // Style AST
148
149
// Traverse AST
150
function walkAST(node, callback) {
151
callback(node);
152
if (node.children) {
153
node.children.forEach(child => walkAST(child, callback));
154
}
155
}
156
157
walkAST(ast, (node) => {
158
if (node.type === 'Text') {
159
console.log('Text node:', node.data);
160
}
161
});
162
```
163
164
### preprocess
165
166
Transforms Svelte component source code using preprocessors before compilation.
167
168
```typescript { .api }
169
/**
170
* Transform component source code using preprocessors
171
* @param source - Component source code
172
* @param preprocessor - Single preprocessor or array of preprocessors
173
* @param options - Preprocessing options
174
* @returns Promise with processed code
175
*/
176
function preprocess(
177
source: string,
178
preprocessor: PreprocessorGroup | PreprocessorGroup[],
179
options?: { filename?: string }
180
): Promise<Processed>;
181
```
182
183
**Usage Examples:**
184
185
```typescript
186
import { preprocess } from "svelte/compiler";
187
188
const source = `
189
<script lang="ts">
190
let count: number = 0;
191
</script>
192
193
<style lang="scss">
194
$primary-color: #ff3e00;
195
196
.button {
197
background: $primary-color;
198
&:hover {
199
opacity: 0.8;
200
}
201
}
202
</style>
203
204
<button class="button" on:click={() => count++}>
205
Count: {count}
206
</button>
207
`;
208
209
// TypeScript and SCSS preprocessing
210
const result = await preprocess(source, [
211
{
212
name: "typescript",
213
script: ({ content, attributes }) => {
214
if (attributes.lang === "ts") {
215
// Transform TypeScript to JavaScript
216
return {
217
code: transformTypeScript(content),
218
map: sourceMap
219
};
220
}
221
}
222
},
223
{
224
name: "scss",
225
style: ({ content, attributes }) => {
226
if (attributes.lang === "scss") {
227
return {
228
code: compileSCSS(content),
229
map: sourceMap
230
};
231
}
232
}
233
}
234
], {
235
filename: "Component.svelte"
236
});
237
238
console.log(result.code); // Processed source ready for compilation
239
```
240
241
### migrate
242
243
Migrates Svelte 4 code to Svelte 5 syntax, converting to runes and modern patterns.
244
245
```typescript { .api }
246
/**
247
* Migrate Svelte 4 code to Svelte 5 runes syntax
248
* @param source - Svelte 4 source code
249
* @param options - Migration options
250
* @returns Migrated code
251
*/
252
function migrate(source: string, options?: {
253
filename?: string;
254
use_ts?: boolean;
255
}): { code: string };
256
```
257
258
**Usage Examples:**
259
260
```typescript
261
import { migrate } from "svelte/compiler";
262
263
const svelte4Source = `
264
<script>
265
export let name = 'world';
266
let count = 0;
267
268
$: doubled = count * 2;
269
$: if (count > 5) {
270
console.log('Count is high!');
271
}
272
273
import { onMount } from 'svelte';
274
275
onMount(() => {
276
console.log('Component mounted');
277
});
278
</script>
279
280
<h1>Hello {name}!</h1>
281
<button on:click={() => count++}>
282
Count: {count}, Doubled: {doubled}
283
</button>
284
`;
285
286
// Migrate to Svelte 5
287
const migrated = migrate(svelte4Source, {
288
filename: "Component.svelte",
289
use_ts: false
290
});
291
292
console.log(migrated.code);
293
// Output will use $state, $derived, $effect, etc.
294
```
295
296
### VERSION
297
298
Current version of the Svelte compiler.
299
300
```typescript { .api }
301
/**
302
* The current Svelte version string
303
*/
304
const VERSION: string;
305
```
306
307
**Usage Examples:**
308
309
```typescript
310
import { VERSION } from "svelte/compiler";
311
312
console.log(`Using Svelte compiler version: ${VERSION}`);
313
314
// Conditional logic based on version
315
const majorVersion = parseInt(VERSION.split('.')[0]);
316
if (majorVersion >= 5) {
317
// Use Svelte 5 features
318
}
319
```
320
321
## Types
322
323
```typescript { .api }
324
interface CompileOptions extends ModuleCompileOptions {
325
/** Component name (inferred from filename if not provided) */
326
name?: string;
327
/** Generate custom element instead of regular component */
328
customElement?: boolean;
329
/** Create accessors for component props */
330
accessors?: boolean;
331
/** Element namespace (html, svg, mathml) */
332
namespace?: 'html' | 'svg' | 'mathml';
333
/** Enable immutable mode optimizations */
334
immutable?: boolean;
335
/** CSS handling strategy */
336
css?: 'injected' | 'external';
337
/** Custom CSS class name hasher */
338
cssHash?: (args: { name: string; filename: string; css: string; hash: (input: string) => string }) => string;
339
/** Preserve HTML comments in output */
340
preserveComments?: boolean;
341
/** Preserve whitespace in templates */
342
preserveWhitespace?: boolean;
343
/** Force runes mode on/off */
344
runes?: boolean;
345
/** Expose version in browser globals */
346
discloseVersion?: boolean;
347
/** Legacy compatibility options */
348
compatibility?: { componentApi?: 4 | 5 };
349
/** Input sourcemap */
350
sourcemap?: object | string;
351
/** Output filename for JS sourcemap */
352
outputFilename?: string;
353
/** Output filename for CSS sourcemap */
354
cssOutputFilename?: string;
355
/** Enable hot module reloading */
356
hmr?: boolean;
357
/** Use modern AST format */
358
modernAst?: boolean;
359
}
360
361
interface ModuleCompileOptions {
362
/** Enable development mode with runtime checks */
363
dev?: boolean;
364
/** Target platform (client, server, or false for syntax-only) */
365
generate?: 'client' | 'server' | false;
366
/** Source filename for debugging */
367
filename?: string;
368
/** Root directory for relative paths */
369
rootDir?: string;
370
/** Function to filter warnings */
371
warningFilter?: (warning: Warning) => boolean;
372
}
373
374
interface CompileResult {
375
/** Generated JavaScript */
376
js: {
377
code: string;
378
map: SourceMap;
379
};
380
/** Generated CSS (null if no styles) */
381
css: null | {
382
code: string;
383
map: SourceMap;
384
hasGlobal: boolean;
385
};
386
/** Compilation warnings */
387
warnings: Warning[];
388
/** Compilation metadata */
389
metadata: {
390
runes: boolean;
391
};
392
/** Component AST */
393
ast: any;
394
}
395
396
interface Processed {
397
/** Transformed source code */
398
code: string;
399
/** Source map */
400
map?: string | object;
401
/** Additional files to watch */
402
dependencies?: string[];
403
/** Updated tag attributes */
404
attributes?: Record<string, string | boolean>;
405
}
406
407
interface PreprocessorGroup {
408
/** Preprocessor name */
409
name?: string;
410
/** Markup preprocessor */
411
markup?: MarkupPreprocessor;
412
/** Style preprocessor */
413
style?: Preprocessor;
414
/** Script preprocessor */
415
script?: Preprocessor;
416
}
417
418
type MarkupPreprocessor = (options: {
419
content: string;
420
filename?: string;
421
}) => Processed | void | Promise<Processed | void>;
422
423
type Preprocessor = (options: {
424
content: string;
425
attributes: Record<string, string | boolean>;
426
markup: string;
427
filename?: string;
428
}) => Processed | void | Promise<Processed | void>;
429
```
430
431
## Best Practices
432
433
1. **Use appropriate targets**: Choose 'client' for browser code, 'server' for SSR
434
2. **Enable dev mode in development**: Provides better error messages and debugging
435
3. **Extract CSS in production**: Use `css: 'external'` for better caching
436
4. **Handle warnings**: Implement `warningFilter` to manage compilation warnings
437
5. **Preserve source maps**: Enable sourcemaps for better debugging experience
438
6. **Use preprocessing**: Leverage preprocessors for TypeScript, SCSS, PostCSS, etc.