0
# @tarojs/runtime
1
2
A comprehensive TypeScript runtime library for the Taro cross-platform framework providing DOM/BOM polyfills, event handling, lifecycle management, and bridge functionality for mini-programs.
3
4
## Package Information
5
6
```typescript
7
import {
8
// BOM APIs
9
document, window, history, location, navigator,
10
URL, URLSearchParams, requestAnimationFrame, cancelAnimationFrame,
11
// DOM APIs
12
TaroElement, TaroNode, TaroText, TaroEvent, createEvent,
13
// Framework Integration
14
createPageConfig, createComponentConfig, getCurrentInstance,
15
// Utilities
16
hydrate, nextTick, eventCenter, throttle, debounce,
17
// Environment & Runtime
18
env, parseUrl, hooks
19
} from '@tarojs/runtime'
20
```
21
22
**Package**: `@tarojs/runtime@4.1.6`
23
**Repository**: [tarojs/taro](https://github.com/NervJS/taro)
24
25
## Overview
26
27
The `@tarojs/runtime` package enables React-like development for multiple platforms including WeChat Mini Programs, Alipay Mini Programs, and web browsers. It bridges the gap between web APIs and mini-program platforms by providing:
28
29
- **Complete DOM/BOM polyfills** for non-web environments
30
- **Virtual DOM implementation** with optimized mini-program rendering
31
- **Cross-platform event system** with bubbling and delegation
32
- **Lifecycle management** for pages and components
33
- **Performance monitoring** and optimization tools
34
- **Context switching** for multi-page applications
35
36
## Architecture
37
38
The runtime creates a unified development environment by:
39
40
1. **Polyfilling Web APIs**: Provides `document`, `window`, `history`, `location` and other browser objects
41
2. **Virtual DOM**: Implements DOM nodes (`TaroElement`, `TaroNode`, `TaroText`) that compile to mini-program data structures
42
3. **Event Bridge**: Translates between web events and mini-program events with proper bubbling
43
4. **Update Batching**: Optimizes rendering with efficient `setData` calls and path-based updates
44
5. **Component Aliasing**: Maps generic components to platform-specific implementations
45
46
## Basic Usage
47
48
### Setting Up a Page
49
50
```typescript { .api }
51
import { createPageConfig, TaroElement } from '@tarojs/runtime'
52
53
// Create a page configuration
54
const pageConfig = createPageConfig(
55
ComponentClass, // React component class
56
'index', // Page name
57
{ title: 'Home' }, // Initial data
58
{ navigationBarTitleText: 'Home Page' } // Page config
59
)
60
61
// The runtime handles lifecycle automatically:
62
// onLoad, onShow, onHide, onReady, onUnload
63
```
64
65
### DOM Manipulation
66
67
```typescript { .api }
68
import { document, TaroElement } from '@tarojs/runtime'
69
70
// Create elements
71
const element: TaroElement = document.createElement('view')
72
element.className = 'container'
73
element.setAttribute('data-test', 'value')
74
75
// Modify content
76
element.textContent = 'Hello World'
77
element.style.setProperty('color', 'red')
78
79
// DOM tree operations
80
document.body.appendChild(element)
81
```
82
83
### Event Handling
84
85
```typescript { .api }
86
import { TaroEvent, eventHandler } from '@tarojs/runtime'
87
88
// Event listener
89
element.addEventListener('tap', (event: TaroEvent) => {
90
console.log('Tapped:', event.target)
91
event.stopPropagation()
92
})
93
94
// Event handler for mini-programs
95
const handler = eventHandler((event) => {
96
// Automatically converts mini-program event to TaroEvent
97
})
98
```
99
100
## Core Type Definitions
101
102
```typescript { .api }
103
import { AppInstance, Router, PageInstance, PageLifeCycle } from '@tarojs/runtime'
104
105
// Main runtime instance
106
interface Current {
107
app: AppInstance | null
108
router: Router | null
109
page: PageInstance | null
110
preloadData?: any
111
}
112
113
// Page instance with lifecycle
114
interface PageInstance extends PageLifeCycle {
115
onLoad?(options: Record<string, unknown>): void
116
onReady?(): void
117
onShow?(): void
118
onHide?(): void
119
onUnload?(): void
120
}
121
122
// DOM node types
123
interface TaroNode extends TaroEventTarget {
124
nodeType: number
125
nodeName: string
126
parentNode: TaroNode | null
127
childNodes: TaroNode[]
128
}
129
130
// Event system
131
interface TaroEvent extends Event {
132
mpEvent?: any // Original mini-program event
133
type: string
134
target: TaroElement
135
currentTarget: TaroElement
136
}
137
```
138
139
## Capabilities
140
141
### Browser Object Model (BOM)
142
Complete browser API polyfills including document, window, history, location, and navigation.
143
144
```typescript { .api }
145
import { window, document, history, location } from '@tarojs/runtime'
146
147
// Window operations
148
window.addEventListener('resize', handler)
149
window.requestAnimationFrame(callback)
150
151
// Document manipulation
152
const element = document.createElement('view')
153
document.getElementById('app')
154
155
// Navigation
156
history.pushState({}, 'New Page', '/new-page')
157
location.href = '/redirect'
158
```
159
160
**[→ Full BOM Documentation](./bom.md)**
161
162
### Document Object Model (DOM)
163
Virtual DOM implementation with nodes, elements, events, and style management optimized for mini-programs.
164
165
```typescript { .api }
166
import { TaroElement, TaroText, Style } from '@tarojs/runtime'
167
168
// Create and modify elements
169
const view = new TaroElement()
170
view.tagName = 'view'
171
view.className = 'container'
172
173
// Text nodes
174
const text = new TaroText('Hello World')
175
view.appendChild(text)
176
177
// Style management
178
view.style.setProperty('background-color', '#fff')
179
view.classList.add('active')
180
```
181
182
**[→ Full DOM Documentation](./dom.md)**
183
184
### Framework Integration
185
DSL functions for page/component configuration, lifecycle management, and instance handling.
186
187
```typescript { .api }
188
import {
189
createPageConfig,
190
createComponentConfig,
191
getCurrentInstance,
192
getPageInstance
193
} from '@tarojs/runtime'
194
195
// Page configuration
196
const config = createPageConfig(MyComponent, 'home', { count: 0 })
197
198
// Get current runtime instance
199
const current = getCurrentInstance()
200
console.log(current.page, current.router)
201
202
// Component lifecycle
203
const componentConfig = createComponentConfig({
204
attached() { /* component ready */ },
205
detached() { /* component cleanup */ }
206
})
207
```
208
209
**[→ Full Framework Integration Documentation](./framework-integration.md)**
210
211
### Utilities & Performance
212
Utility functions, performance monitoring, event emitters, and optimization tools.
213
214
```typescript { .api }
215
import {
216
throttle,
217
debounce,
218
nextTick,
219
hydrate,
220
eventCenter,
221
perf
222
} from '@tarojs/runtime'
223
224
// Performance utilities
225
const throttledFn = throttle(expensiveFunction, 250)
226
const debouncedFn = debounce(updateFunction, 500)
227
228
// Async operations
229
nextTick(() => {
230
// Execute after next DOM update
231
})
232
233
// Performance monitoring
234
perf.start('render')
235
// ... rendering work
236
perf.stop('render')
237
```
238
239
**[→ Full Utilities Documentation](./utilities.md)**
240
241
### Type Definitions
242
Core interfaces, type definitions, and contracts for the runtime system.
243
244
```typescript { .api }
245
// Instance types
246
interface Instance<T = Record<string, any>> extends Component<T>, PageInstance
247
interface ReactPageInstance<T = PageProps> extends Component<T>, PageInstance
248
249
// Event types
250
interface MpEvent { /* mini-program event */ }
251
interface EventOptions { /* event construction options */ }
252
253
// Update types
254
interface UpdatePayload { /* DOM update payload */ }
255
interface MiniData { /* mini-program data structure */ }
256
```
257
258
**[→ Full Types Documentation](./types.md)**
259
260
## Environment Support
261
262
- **Mini Programs**: WeChat, Alipay, ByteDance, Baidu, QQ
263
- **Web Browsers**: Chrome, Firefox, Safari, Edge
264
- **Mobile Apps**: React Native (via Taro)
265
- **Desktop Apps**: Electron (via Taro)
266
267
## Performance Features
268
269
- **Update Batching**: Efficient DOM updates with `setData` optimization
270
- **Path-based Updates**: Incremental changes using dot-notation paths
271
- **Component Aliasing**: Platform-specific component mapping
272
- **Event Delegation**: Optimized event handling with ancestor checking
273
- **Context Switching**: Automatic state management for multi-page apps
274
- **Mutation Observation**: Change tracking with lifecycle integration
275
276
The runtime enables unified cross-platform development while maintaining optimal performance on each target platform.