0
# Core Framework APIs
1
2
Essential framework utilities including the main Taro object, app lifecycle management, and system utilities that form the foundation of Taro H5 applications.
3
4
## Capabilities
5
6
### Main Taro Object
7
8
The central Taro object provides core utilities for pixel transformation, environment detection, and application information.
9
10
```typescript { .api }
11
/**
12
* Main Taro object exported as default from @tarojs/taro-h5
13
* Contains core utilities and framework integration
14
*/
15
interface TaroCore {
16
// Pixel transformation utilities
17
pxTransform(size: number): string;
18
initPxTransform(config: PxTransformConfig): void;
19
20
// Application information
21
getAppInfo(): AppInfo;
22
canIUseWebp(): boolean;
23
24
// Environment and framework integration
25
getEnv(): string;
26
getCurrentInstance(): ComponentInstance;
27
getApp<T>(): T;
28
getCurrentPages(): PageInstance[];
29
30
// Event system
31
eventCenter: EventCenter;
32
Events: typeof Events;
33
34
// Framework utilities
35
nextTick(callback: Function): void;
36
options: Record<string, any>;
37
history: History;
38
39
// Interceptor system
40
interceptors: Interceptors;
41
interceptorify: (fn: Function) => Function;
42
43
// Component behavior system
44
Behavior: (behavior: any) => any;
45
46
// Current context
47
Current: CurrentContext;
48
49
// Preload functionality
50
preload: (data: any) => void;
51
52
// Constants
53
ENV_TYPE: typeof ENV_TYPE;
54
Link: any;
55
56
// Plugin system (not supported in H5)
57
requirePlugin(name: string): never;
58
}
59
```
60
61
**Usage Examples:**
62
63
```typescript
64
import Taro from "@tarojs/taro-h5";
65
66
// Initialize pixel transformation
67
Taro.initPxTransform({
68
designWidth: 750,
69
deviceRatio: {
70
640: 1.17,
71
750: 1,
72
828: 0.905
73
}
74
});
75
76
// Transform pixels
77
const transformedSize = Taro.pxTransform(100); // Returns "1rem" or similar
78
79
// Get app information
80
const appInfo = Taro.getAppInfo();
81
console.log(`Platform: ${appInfo.platform}, Version: ${appInfo.taroVersion}`);
82
83
// Check WebP support
84
if (Taro.canIUseWebp()) {
85
console.log('WebP images are supported');
86
}
87
88
// Get environment
89
const env = Taro.getEnv();
90
console.log(`Running in: ${env}`); // 'WEB' for H5
91
92
// Get current component instance
93
const instance = Taro.getCurrentInstance();
94
console.log(instance.router?.params);
95
```
96
97
### Pixel Transformation
98
99
Utilities for converting design pixels to responsive units based on device characteristics.
100
101
```typescript { .api }
102
/**
103
* Initialize pixel transformation configuration
104
* @param config - Configuration options for pixel transformation
105
*/
106
function initPxTransform(config: PxTransformConfig): void;
107
108
/**
109
* Transform pixels using configured settings
110
* @param size - Pixel size to transform
111
* @returns Transformed size string with unit
112
*/
113
function pxTransform(size: number): string;
114
115
interface PxTransformConfig {
116
/** Design width in pixels (default: 750) */
117
designWidth?: number;
118
/** Device ratio mapping (default: {640: 1.17, 750: 1, 828: 0.905}) */
119
deviceRatio?: Record<number, number>;
120
/** Base font size for rem calculations (default: 20) */
121
baseFontSize?: number;
122
/** Decimal precision for transformed values (default: 5) */
123
unitPrecision?: number;
124
/** Target unit for transformation (default: 'rem') */
125
targetUnit?: 'rem' | 'px' | 'vw';
126
}
127
```
128
129
### Application Information
130
131
Utilities for retrieving application and environment information.
132
133
```typescript { .api }
134
/**
135
* Get comprehensive application information
136
* @returns Object containing platform and version details
137
*/
138
function getAppInfo(): AppInfo;
139
140
/**
141
* Check if WebP image format is supported in current browser
142
* @returns true if WebP is supported, false otherwise
143
*/
144
function canIUseWebp(): boolean;
145
146
interface AppInfo {
147
/** Platform identifier (always 'WEB' for H5) */
148
platform: string;
149
/** Taro framework version string */
150
taroVersion: string;
151
/** Current design width setting */
152
designWidth: number;
153
}
154
```
155
156
### Framework Integration
157
158
Core framework integration utilities for component and page management.
159
160
```typescript { .api }
161
/**
162
* Get current component instance with context information
163
* @returns Current component instance or undefined
164
*/
165
function getCurrentInstance(): ComponentInstance | undefined;
166
167
/**
168
* Get the current app instance
169
* @returns App instance with type information
170
*/
171
function getApp<T = any>(): T;
172
173
/**
174
* Get current page stack
175
* @returns Array of page instances in navigation order
176
*/
177
function getCurrentPages(): PageInstance[];
178
179
/**
180
* Get current environment type
181
* @returns Environment identifier string
182
*/
183
function getEnv(): string;
184
185
/**
186
* Schedule callback for next tick
187
* @param callback - Function to execute on next tick
188
*/
189
function nextTick(callback: Function): void;
190
191
interface ComponentInstance {
192
/** Associated page context */
193
page?: any;
194
/** Router information */
195
router?: {
196
params: Record<string, string>;
197
path: string;
198
};
199
/** Component scope */
200
scope?: any;
201
/** Additional component properties */
202
[key: string]: any;
203
}
204
205
interface PageInstance {
206
/** Page route path */
207
route: string;
208
/** Page query parameters */
209
options: Record<string, string>;
210
/** Additional page properties */
211
[key: string]: any;
212
}
213
```
214
215
### Event System
216
217
Centralized event management system for cross-component communication.
218
219
```typescript { .api }
220
/**
221
* Global event center for pub/sub communication
222
*/
223
interface EventCenter {
224
on(event: string, callback: Function): void;
225
off(event: string, callback?: Function): void;
226
trigger(event: string, ...args: any[]): void;
227
once(event: string, callback: Function): void;
228
}
229
230
/**
231
* Events class for creating event instances
232
*/
233
class Events {
234
on(event: string, callback: Function): void;
235
off(event: string, callback?: Function): void;
236
trigger(event: string, ...args: any[]): void;
237
once(event: string, callback: Function): void;
238
}
239
```
240
241
### Interceptor System
242
243
Request and function interceptor system for aspect-oriented programming.
244
245
```typescript { .api }
246
/**
247
* Global interceptors object containing request interceptors
248
*/
249
interface Interceptors {
250
request: {
251
use(fulfilled?: Function, rejected?: Function): number;
252
eject(id: number): void;
253
};
254
}
255
256
/**
257
* Create an intercepted version of a function
258
* @param fn - Function to wrap with interceptors
259
* @returns Intercepted function
260
*/
261
function interceptorify(fn: Function): Function;
262
```
263
264
### Environment Constants
265
266
Environment type constants for runtime detection.
267
268
```typescript { .api }
269
/**
270
* Environment type constants
271
*/
272
declare const ENV_TYPE: {
273
WEAPP: 'WEAPP'; // WeChat Mini Program
274
WEB: 'WEB'; // Web/H5 environment
275
RN: 'RN'; // React Native
276
SWAN: 'SWAN'; // Baidu Smart Program
277
ALIPAY: 'ALIPAY'; // Alipay Mini Program
278
TT: 'TT'; // ByteDance Mini Program
279
QQ: 'QQ'; // QQ Mini Program
280
JD: 'JD'; // JD Mini Program
281
};
282
283
/**
284
* Current application context
285
*/
286
interface CurrentContext {
287
app: any;
288
page: any;
289
component: any;
290
router: {
291
params: Record<string, string>;
292
path: string;
293
};
294
[key: string]: any;
295
}
296
```
297
298
### Component Behavior System
299
300
Component behavior definition system for reusable component logic.
301
302
```typescript { .api }
303
/**
304
* Define reusable component behavior
305
* Note: Limited functionality in H5 environment
306
* @param behavior - Behavior definition object
307
* @returns Behavior constructor
308
*/
309
function Behavior(behavior: BehaviorDefinition): any;
310
311
interface BehaviorDefinition {
312
properties?: Record<string, any>;
313
data?: Record<string, any>;
314
methods?: Record<string, Function>;
315
behaviors?: any[];
316
created?(): void;
317
attached?(): void;
318
ready?(): void;
319
detached?(): void;
320
[key: string]: any;
321
}
322
```
323
324
### Plugin System
325
326
Plugin requirement system (not supported in H5 environment).
327
328
```typescript { .api }
329
/**
330
* Require a plugin (not supported in H5)
331
* @param name - Plugin name
332
* @throws Always throws "not supported" error in H5
333
*/
334
function requirePlugin(name: string): never;
335
```
336
337
**Note**: The plugin system is specific to Mini Program environments and is not available in H5. This function will always throw an error indicating the feature is not supported.
338
339
## Integration Examples
340
341
### Basic Framework Setup
342
343
```typescript
344
import Taro from "@tarojs/taro-h5";
345
346
// Configure pixel transformation for responsive design
347
Taro.initPxTransform({
348
designWidth: 750,
349
deviceRatio: {
350
640: 1.17,
351
750: 1,
352
828: 0.905
353
},
354
baseFontSize: 20,
355
targetUnit: 'rem'
356
});
357
358
// Set up global event listeners
359
Taro.eventCenter.on('user:login', (userData) => {
360
console.log('User logged in:', userData);
361
});
362
363
// Check environment
364
if (Taro.getEnv() === Taro.ENV_TYPE.WEB) {
365
console.log('Running in web environment');
366
}
367
```
368
369
### Component Context Usage
370
371
```typescript
372
import Taro from "@tarojs/taro-h5";
373
374
function MyComponent() {
375
// Get current instance context
376
const instance = Taro.getCurrentInstance();
377
378
// Access router parameters
379
const { params } = instance?.router || {};
380
381
// Get current page stack
382
const pages = Taro.getCurrentPages();
383
const currentPage = pages[pages.length - 1];
384
385
// Use next tick for DOM updates
386
Taro.nextTick(() => {
387
console.log('DOM updated');
388
});
389
390
return <div>Component content</div>;
391
}
392
```
393
394
### Event Communication
395
396
```typescript
397
import Taro from "@tarojs/taro-h5";
398
399
// Create custom events instance
400
const customEvents = new Taro.Events();
401
402
// Component A - emit event
403
customEvents.trigger('data:updated', { id: 1, name: 'Updated' });
404
405
// Component B - listen for event
406
customEvents.on('data:updated', (data) => {
407
console.log('Received data:', data);
408
});
409
410
// Global event communication
411
Taro.eventCenter.trigger('app:ready', { timestamp: Date.now() });
412
```