0
# Runtime Utilities
1
2
Runtime functions for asset management, mode handling, task scheduling, and component utilities. These utilities provide essential runtime functionality for Stencil components and applications.
3
4
## Capabilities
5
6
### Asset Management
7
8
Functions for managing asset paths and resources in Stencil applications.
9
10
```typescript { .api }
11
/**
12
* Get the base path to where assets can be found
13
* @param path - Asset path to resolve
14
* @returns Full asset path with base URL
15
*/
16
function getAssetPath(path: string): string;
17
18
/**
19
* Set the base path where assets can be found
20
* @param path - Base asset path to set
21
* @returns The set path
22
*/
23
function setAssetPath(path: string): string;
24
```
25
26
**Usage Examples:**
27
28
```typescript
29
import { getAssetPath, setAssetPath } from '@stencil/core';
30
31
// Set asset path for custom elements build
32
setAssetPath(import.meta.url);
33
34
// Get asset path for use in component
35
export class MyComponent {
36
render() {
37
return (
38
<div>
39
<img src={getAssetPath('./assets/logo.png')} alt="Logo" />
40
</div>
41
);
42
}
43
}
44
```
45
46
### Mode Management
47
48
Functions for handling style modes and environment-specific styling.
49
50
```typescript { .api }
51
/**
52
* Get the current mode for style resolution
53
* @param ref - Reference to get mode for
54
* @returns Current mode or undefined
55
*/
56
function getMode<T = string | undefined>(ref: any): T;
57
58
/**
59
* Set the mode resolution handler
60
* @param handler - Function to resolve mode for elements
61
*/
62
function setMode(handler: ResolutionHandler): void;
63
64
type ResolutionHandler = (elm: HTMLElement) => string | undefined | null;
65
```
66
67
**Usage Examples:**
68
69
```typescript
70
import { setMode, getMode } from '@stencil/core';
71
72
// Set mode resolver based on theme attribute
73
setMode((elm) => {
74
return elm.closest('[theme]')?.getAttribute('theme') || 'default';
75
});
76
77
// Use mode in component
78
export class MyComponent {
79
componentDidLoad() {
80
const currentMode = getMode(this.el);
81
console.log('Current mode:', currentMode);
82
}
83
}
84
```
85
86
### Build Conditionals
87
88
Constants for build-time feature detection and conditional compilation.
89
90
```typescript { .api }
91
/**
92
* Build-time conditionals for feature detection
93
*/
94
interface UserBuildConditionals {
95
/** Whether running in development mode */
96
isDev: boolean;
97
/** Whether running in browser environment */
98
isBrowser: boolean;
99
/** Whether running in server environment */
100
isServer: boolean;
101
/** Whether running in testing environment */
102
isTesting: boolean;
103
}
104
105
/**
106
* Build conditionals object
107
*/
108
declare const Build: UserBuildConditionals;
109
110
/**
111
* Environment variables from stencil.config.ts
112
*/
113
declare const Env: { [prop: string]: string | undefined };
114
```
115
116
**Usage Examples:**
117
118
```typescript
119
import { Build, Env } from '@stencil/core';
120
121
export class MyComponent {
122
componentDidLoad() {
123
if (Build.isDev) {
124
console.log('Development mode active');
125
}
126
127
if (Build.isBrowser) {
128
// Browser-specific code
129
window.addEventListener('resize', this.handleResize);
130
}
131
132
if (Build.isServer) {
133
// Server-side rendering code
134
this.setupSSRDefaults();
135
}
136
137
// Use environment variables
138
const apiUrl = Env.API_URL || 'https://api.example.com';
139
}
140
}
141
```
142
143
### Task Scheduling
144
145
Functions for scheduling DOM read and write operations to optimize performance.
146
147
```typescript { .api }
148
/**
149
* Schedule a DOM-write task for optimal performance
150
* @param task - Callback to execute during write phase
151
*/
152
function writeTask(task: RafCallback): void;
153
154
/**
155
* Schedule a DOM-read task for optimal performance
156
* @param task - Callback to execute during read phase
157
*/
158
function readTask(task: RafCallback): void;
159
160
interface RafCallback {
161
(timeStamp: number): void;
162
}
163
164
/**
165
* Task queue API for advanced scheduling
166
*/
167
interface QueueApi {
168
/** Schedule a callback for next tick */
169
tick: (cb: RafCallback) => void;
170
/** Schedule a DOM read task */
171
read: (cb: RafCallback) => void;
172
/** Schedule a DOM write task */
173
write: (cb: RafCallback) => void;
174
/** Clear all queued tasks */
175
clear?: () => void;
176
/** Flush all queued tasks immediately */
177
flush?: (cb?: () => void) => void;
178
}
179
```
180
181
**Usage Examples:**
182
183
```typescript
184
import { writeTask, readTask } from '@stencil/core';
185
186
export class MyComponent {
187
@Element() el: HTMLElement;
188
189
updateLayout() {
190
// First read DOM properties
191
readTask(() => {
192
const rect = this.el.getBoundingClientRect();
193
const scrollTop = window.scrollY;
194
195
// Then write DOM changes
196
writeTask(() => {
197
this.el.style.transform = `translateY(${scrollTop}px)`;
198
this.el.style.width = `${rect.width}px`;
199
});
200
});
201
}
202
203
@Listen('scroll', { target: 'window' })
204
handleScroll() {
205
this.updateLayout();
206
}
207
}
208
```
209
210
### Component Utilities
211
212
Utilities for working with component instances and lifecycle management.
213
214
```typescript { .api }
215
/**
216
* Get Stencil element reference from any reference
217
* @param ref - Reference to get element for
218
* @returns HTMLStencilElement instance
219
*/
220
function getElement(ref: any): HTMLStencilElement;
221
222
/**
223
* Force a component to re-render
224
* @param ref - Component reference to force update
225
*/
226
function forceUpdate(ref: any): void;
227
228
/**
229
* Get the current rendering reference
230
* @returns Current rendering reference
231
*/
232
function getRenderingRef(): any;
233
234
/**
235
* Enhanced HTML element with Stencil capabilities
236
*/
237
interface HTMLStencilElement extends HTMLElement {
238
/** Promise that resolves when component is ready */
239
componentOnReady(): Promise<HTMLStencilElement>;
240
}
241
```
242
243
**Usage Examples:**
244
245
```typescript
246
import { getElement, forceUpdate } from '@stencil/core';
247
248
export class MyComponent {
249
@Element() el: HTMLElement;
250
private data: any[] = [];
251
252
async componentDidLoad() {
253
const stencilEl = getElement(this.el);
254
await stencilEl.componentOnReady();
255
console.log('Component is ready');
256
}
257
258
@Method()
259
async updateData(newData: any[]) {
260
this.data = newData;
261
// Force re-render with new data
262
forceUpdate(this);
263
}
264
265
@Method()
266
async refresh() {
267
// Force component to re-render
268
forceUpdate(this.el);
269
}
270
}
271
```
272
273
### Platform Configuration
274
275
Functions for configuring platform-specific behavior and security settings.
276
277
```typescript { .api }
278
/**
279
* Set Content Security Policy nonce for dynamic styles and scripts
280
* @param nonce - Nonce value for CSP
281
*/
282
function setNonce(nonce: string): void;
283
284
/**
285
* Set global error handler for unhandled exceptions
286
* @param handler - Error handler function
287
*/
288
function setErrorHandler(handler: ErrorHandler): void;
289
290
type ErrorHandler = (err: any, element?: HTMLElement) => void;
291
292
/**
293
* Set platform-specific helper functions
294
* @param helpers - Platform helper functions
295
*/
296
function setPlatformHelpers(helpers: PlatformHelpers): void;
297
298
interface PlatformHelpers {
299
/** Jump function for task scheduling */
300
jmp?: (c: any) => any;
301
/** RequestAnimationFrame implementation */
302
raf?: (c: any) => number;
303
/** Add event listener implementation */
304
ael?: (el: any, eventName: string, listener: any, options: any) => void;
305
/** Remove event listener implementation */
306
rel?: (el: any, eventName: string, listener: any, options: any) => void;
307
/** Create custom event implementation */
308
ce?: (eventName: string, opts?: any) => any;
309
}
310
```
311
312
**Usage Examples:**
313
314
```typescript
315
import { setNonce, setErrorHandler, setPlatformHelpers } from '@stencil/core';
316
317
// Set CSP nonce for dynamic styles
318
setNonce('abc123xyz');
319
320
// Set global error handler
321
setErrorHandler((error, element) => {
322
console.error('Stencil component error:', error);
323
if (element) {
324
console.error('Error occurred in element:', element.tagName);
325
}
326
327
// Send to error reporting service
328
errorReportingService.report(error, {
329
component: element?.tagName,
330
url: window.location.href
331
});
332
});
333
334
// Set custom platform helpers for non-standard environments
335
setPlatformHelpers({
336
raf: (callback) => {
337
// Custom RAF implementation for non-browser environments
338
return customScheduler.schedule(callback);
339
},
340
ael: (el, eventName, listener, options) => {
341
// Custom event listener implementation
342
customEventSystem.addEventListener(el, eventName, listener, options);
343
}
344
});
345
```
346
347
### Virtual DOM Utilities
348
349
The render function for manually rendering virtual DOM trees.
350
351
```typescript { .api }
352
/**
353
* Render a virtual DOM tree to a container element
354
* @param vnode - Virtual DOM tree to render
355
* @param container - Container element to render into
356
*/
357
function render(vnode: VNode, container: Element): void;
358
```
359
360
**Usage Example:**
361
362
```typescript
363
import { render, h } from '@stencil/core';
364
365
// Render virtual DOM tree to specific container
366
const vnode = (
367
<div>
368
<h1>Hello, World!</h1>
369
<p>This is rendered with the render function</p>
370
</div>
371
);
372
373
const container = document.getElementById('app');
374
render(vnode, container);
375
376
// Or using h() function directly
377
const vnodeWithH = h('div', null, [
378
h('h1', null, 'Hello, World!'),
379
h('p', null, 'This is rendered with h() and render()')
380
]);
381
382
render(vnodeWithH, container);
383
```
384
385
### Performance Utilities
386
387
Utilities for performance monitoring and optimization.
388
389
```typescript { .api }
390
/**
391
* Performance monitoring for component operations
392
*/
393
interface PerformanceEntry {
394
name: string;
395
startTime: number;
396
duration: number;
397
}
398
399
/**
400
* Custom elements define options for performance tuning
401
*/
402
interface CustomElementsDefineOptions {
403
/** Components to exclude from definition */
404
exclude?: string[];
405
/** Resources URL for assets */
406
resourcesUrl?: string;
407
/** Use synchronous queue for updates */
408
syncQueue?: boolean;
409
/** Transform tag names during definition */
410
transformTagName?: (tagName: string) => string;
411
/** Custom jump function */
412
jmp?: (c: Function) => any;
413
/** Custom RAF function */
414
raf?: (c: FrameRequestCallback) => number;
415
/** Custom add event listener */
416
ael?: (
417
el: EventTarget,
418
eventName: string,
419
listener: EventListenerOrEventListenerObject,
420
options: boolean | AddEventListenerOptions,
421
) => void;
422
/** Custom remove event listener */
423
rel?: (
424
el: EventTarget,
425
eventName: string,
426
listener: EventListenerOrEventListenerObject,
427
options: boolean | AddEventListenerOptions,
428
) => void;
429
/** Custom create event */
430
ce?: (eventName: string, opts?: any) => CustomEvent;
431
}
432
```
433
434
**Usage Example:**
435
436
```typescript
437
// Custom elements definition with performance options
438
const defineOptions: CustomElementsDefineOptions = {
439
// Exclude certain components from auto-definition
440
exclude: ['my-heavy-component'],
441
442
// Use synchronous queue for immediate updates
443
syncQueue: true,
444
445
// Transform tag names for compatibility
446
transformTagName: (tagName) => {
447
return tagName.replace(/^my-/, 'custom-');
448
}
449
};
450
```