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

context.md docs/

1
# Context Management
2
3
Svelte's context API provides a way to share data between parent and child components without explicitly passing props through every level of the component tree. Context is ideal for themes, user authentication, and other cross-cutting concerns.
4
5
## Capabilities
6
7
### setContext
8
9
Associates an arbitrary context object with the current component and the specified key. Must be called during component initialization.
10
11
```typescript { .api }
12
/**
13
* Associates an arbitrary context object with the current component and the specified key
14
* @param key - Context key (can be any value, often string or Symbol)
15
* @param context - Context value to store
16
* @returns The context value
17
*/
18
function setContext<T>(key: any, context: T): T;
19
```
20
21
**Usage Examples:**
22
23
```typescript
24
import { setContext } from "svelte";
25
26
// Parent component
27
const THEME_KEY = "theme";
28
29
const theme = {
30
colors: {
31
primary: "#ff3e00",
32
secondary: "#40b3ff"
33
},
34
fonts: {
35
body: "Arial, sans-serif",
36
heading: "Georgia, serif"
37
}
38
};
39
40
// Set context for children
41
setContext(THEME_KEY, theme);
42
43
// Using Symbol keys for uniqueness
44
const API_KEY = Symbol("api");
45
setContext(API_KEY, {
46
baseUrl: "https://api.example.com",
47
headers: { "Authorization": `Bearer ${token}` }
48
});
49
50
// Reactive context (context value itself can be reactive)
51
let user = $state({ name: "Alice", role: "admin" });
52
setContext("user", user);
53
```
54
55
### getContext
56
57
Retrieves the context associated with the specified key from the nearest parent component.
58
59
```typescript { .api }
60
/**
61
* Retrieves the context associated with the specified key
62
* @param key - Context key to look up
63
* @returns Context value or undefined if not found
64
*/
65
function getContext<T>(key: any): T;
66
```
67
68
**Usage Examples:**
69
70
```typescript
71
import { getContext } from "svelte";
72
73
// Child component
74
const THEME_KEY = "theme";
75
76
// Get theme from parent context
77
const theme = getContext(THEME_KEY);
78
79
if (theme) {
80
console.log("Primary color:", theme.colors.primary);
81
}
82
83
// Type-safe context access with TypeScript
84
interface ThemeContext {
85
colors: { primary: string; secondary: string };
86
fonts: { body: string; heading: string };
87
}
88
89
const theme: ThemeContext = getContext(THEME_KEY);
90
91
// Using Symbol keys
92
const API_KEY = Symbol("api");
93
const api = getContext(API_KEY);
94
95
// Fallback for missing context
96
const settings = getContext("settings") || { defaultSetting: true };
97
98
// Context in reactive expressions
99
let theme = getContext("theme");
100
let primaryColor = $derived(theme?.colors?.primary || "#000");
101
```
102
103
### hasContext
104
105
Checks whether a given key has been set in the context of a parent component.
106
107
```typescript { .api }
108
/**
109
* Checks whether a given key has been set in the context of a parent component
110
* @param key - Context key to check
111
* @returns true if context exists, false otherwise
112
*/
113
function hasContext(key: any): boolean;
114
```
115
116
**Usage Examples:**
117
118
```typescript
119
import { hasContext, getContext } from "svelte";
120
121
// Check if context exists before using
122
if (hasContext("theme")) {
123
const theme = getContext("theme");
124
// Safe to use theme
125
} else {
126
// Handle missing theme context
127
console.warn("No theme context provided");
128
}
129
130
// Conditional feature activation
131
const hasAnalytics = hasContext("analytics");
132
if (hasAnalytics) {
133
const analytics = getContext("analytics");
134
analytics.track("page_view");
135
}
136
137
// Optional context consumption
138
function useOptionalContext(key, fallback) {
139
return hasContext(key) ? getContext(key) : fallback;
140
}
141
142
const userPrefs = useOptionalContext("preferences", { lang: "en" });
143
```
144
145
### getAllContexts
146
147
Returns a Map of all contexts from the current component. Useful for debugging or context forwarding.
148
149
```typescript { .api }
150
/**
151
* Returns a Map of all context entries from the current component
152
* @returns Map containing all context key-value pairs
153
*/
154
function getAllContexts<T extends Map<any, any> = Map<any, any>>(): T;
155
```
156
157
**Usage Examples:**
158
159
```typescript
160
import { getAllContexts, setContext } from "svelte";
161
162
// Debug utility to log all available contexts
163
function debugContexts() {
164
const contexts = getAllContexts();
165
console.log("Available contexts:", contexts);
166
167
for (const [key, value] of contexts) {
168
console.log(`Context ${key}:`, value);
169
}
170
}
171
172
// Context forwarding component
173
function forwardAllContexts(targetComponent) {
174
const contexts = getAllContexts();
175
176
// Forward all contexts to child component
177
for (const [key, value] of contexts) {
178
setContext(key, value);
179
}
180
}
181
182
// Context merging utility
183
function mergeContexts(additionalContexts) {
184
const existingContexts = getAllContexts();
185
186
return new Map([
187
...existingContexts,
188
...Object.entries(additionalContexts)
189
]);
190
}
191
```
192
193
## Usage Patterns
194
195
### Theme Provider Pattern
196
197
```typescript
198
// ThemeProvider.svelte
199
import { setContext } from "svelte";
200
201
let { theme, children } = $props();
202
203
setContext("theme", theme);
204
205
// Template: {@render children()}
206
207
// Child component
208
import { getContext } from "svelte";
209
210
const theme = getContext("theme");
211
const primaryColor = theme.colors.primary;
212
```
213
214
### Store Provider Pattern
215
216
```typescript
217
// StoreProvider.svelte
218
import { setContext } from "svelte";
219
import { writable } from "svelte/store";
220
221
// Create stores
222
const userStore = writable(null);
223
const cartStore = writable([]);
224
225
// Provide stores via context
226
setContext("stores", {
227
user: userStore,
228
cart: cartStore
229
});
230
231
// Child component
232
import { getContext } from "svelte";
233
234
const stores = getContext("stores");
235
const user = stores.user;
236
const cart = stores.cart;
237
238
// Use with auto-subscription
239
// let currentUser = $user;
240
// let cartItems = $cart;
241
```
242
243
### API Client Pattern
244
245
```typescript
246
// APIProvider.svelte
247
import { setContext } from "svelte";
248
249
class APIClient {
250
constructor(baseUrl, token) {
251
this.baseUrl = baseUrl;
252
this.token = token;
253
}
254
255
async fetch(endpoint, options = {}) {
256
return fetch(`${this.baseUrl}${endpoint}`, {
257
...options,
258
headers: {
259
"Authorization": `Bearer ${this.token}`,
260
...options.headers
261
}
262
});
263
}
264
}
265
266
const apiClient = new APIClient("https://api.example.com", token);
267
setContext("api", apiClient);
268
269
// Child component
270
import { getContext } from "svelte";
271
272
const api = getContext("api");
273
274
async function loadData() {
275
const response = await api.fetch("/data");
276
return response.json();
277
}
278
```
279
280
## Types
281
282
```typescript { .api }
283
// Context key can be any type
284
type ContextKey = any;
285
286
// Context value can be any type
287
type ContextValue = any;
288
289
// Map type for getAllContexts
290
type ContextMap = Map<ContextKey, ContextValue>;
291
```
292
293
## Best Practices
294
295
1. **Use descriptive keys**: Use strings or Symbols for context keys to avoid collisions
296
2. **Set context early**: Call `setContext` during component initialization, not in effects
297
3. **Provide fallbacks**: Check for context existence with `hasContext` or provide defaults
298
4. **Keep context focused**: Don't put everything in context - use it for cross-cutting concerns
299
5. **Document context contracts**: Clearly document what context keys your components expect
300
6. **Use TypeScript**: Type your context objects for better developer experience
301
7. **Consider Symbol keys**: Use Symbol keys for private contexts to prevent accidental access