0
# Platform Abstraction
1
2
Abstract base classes for implementing custom platforms with transaction-based build processes, platform-specific configurations, and support for both mini-program and web targets.
3
4
## Capabilities
5
6
### TaroPlatform Base Class
7
8
Abstract base class for all platform implementations providing common functionality and transaction management.
9
10
```typescript { .api }
11
/**
12
* Abstract base class for all platform implementations
13
*/
14
abstract class TaroPlatform<T extends TConfig = TConfig> {
15
protected ctx: IPluginContext;
16
protected config: T;
17
protected helper: IPluginContext['helper'];
18
protected compiler: string;
19
20
abstract platformType: PLATFORM_TYPE;
21
abstract platform: string;
22
abstract runtimePath: string | string[];
23
24
behaviorsName?: string;
25
26
protected setupTransaction: Transaction<this>;
27
protected buildTransaction: Transaction<this>;
28
29
constructor(ctx: IPluginContext, config: T);
30
getConfig(): T;
31
abstract start(): Promise<void>;
32
}
33
34
enum PLATFORM_TYPE {
35
MINI = 'MINI',
36
WEB = 'WEB'
37
}
38
```
39
40
**Usage for Custom Platform:**
41
42
```typescript
43
import { TaroPlatform, PLATFORM_TYPE } from "@tarojs/service";
44
45
class MyCustomPlatform extends TaroPlatform {
46
platformType = PLATFORM_TYPE.WEB;
47
platform = 'my-platform';
48
runtimePath = '@tarojs/runtime';
49
50
async start() {
51
// Custom platform build logic
52
await this.setupTransaction.perform(this.setupPlatform, this);
53
await this.buildTransaction.perform(this.buildPlatform, this);
54
}
55
56
private setupPlatform() {
57
this.emptyOutputDir();
58
// Additional setup logic
59
}
60
61
private buildPlatform() {
62
// Build implementation
63
}
64
}
65
```
66
67
### TaroPlatformBase for Mini-Programs
68
69
Base class specifically for mini-program platform implementations with template support and project config generation.
70
71
```typescript { .api }
72
/**
73
* Base class for mini-program platform implementations
74
*/
75
abstract class TaroPlatformBase<T extends TConfig = TConfig> extends TaroPlatform<T> {
76
platformType: PLATFORM_TYPE.MINI;
77
78
abstract globalObject: string;
79
abstract fileType: IFileType;
80
abstract template: RecursiveTemplate | UnRecursiveTemplate;
81
82
taroComponentsPath: string;
83
projectConfigJson?: string;
84
85
start(): Promise<void>;
86
}
87
88
interface IFileType {
89
templ: string; // Template file extension
90
style: string; // Style file extension
91
script: string; // Script file extension
92
config: string; // Config file extension
93
xs?: string; // Script extension for some platforms
94
}
95
```
96
97
**Usage for Mini-Program Platform:**
98
99
```typescript
100
import { TaroPlatformBase, PLATFORM_TYPE } from "@tarojs/service";
101
102
class WeappPlatform extends TaroPlatformBase {
103
platform = 'weapp';
104
globalObject = 'wx';
105
projectConfigJson = 'project.config.json';
106
107
fileType = {
108
templ: '.wxml',
109
style: '.wxss',
110
script: '.js',
111
config: '.json'
112
};
113
114
template = new RecursiveTemplate(); // Template configuration
115
runtimePath = '@tarojs/runtime';
116
}
117
```
118
119
### TaroPlatformWeb for Web Platforms
120
121
Base class for web platform implementations with development server configuration and bundle optimization.
122
123
```typescript { .api }
124
/**
125
* Base class for web platform implementations
126
*/
127
abstract class TaroPlatformWeb<T extends TConfig = TConfig> extends TaroPlatform<T> {
128
platformType: PLATFORM_TYPE.WEB;
129
130
start(): Promise<void>;
131
}
132
```
133
134
**Usage for Web Platform:**
135
136
```typescript
137
import { TaroPlatformWeb } from "@tarojs/service";
138
139
class H5Platform extends TaroPlatformWeb {
140
platform = 'h5';
141
runtimePath = '@tarojs/runtime';
142
143
// Inherits web-specific build logic from TaroPlatformWeb
144
}
145
```
146
147
### Transaction Management
148
149
Transaction system for wrapping platform operations with setup and teardown logic.
150
151
```typescript { .api }
152
/**
153
* Transaction manager for wrapping platform operations
154
*/
155
class Transaction<T = TaroPlatform> {
156
wrappers: IWrapper[];
157
158
perform(fn: Func, scope: T, ...args: any[]): Promise<void>;
159
addWrapper(wrapper: IWrapper): void;
160
}
161
162
interface IWrapper {
163
init?(): void;
164
close?(): void;
165
}
166
```
167
168
The transaction system allows platforms to:
169
- Execute initialization logic before operations
170
- Ensure cleanup occurs after operations
171
- Wrap multiple operations with consistent setup/teardown
172
173
**Usage Example:**
174
175
```typescript
176
// Add custom wrapper to setup transaction
177
this.setupTransaction.addWrapper({
178
init() {
179
console.log('Starting setup...');
180
},
181
close() {
182
console.log('Setup complete');
183
}
184
});
185
```
186
187
### Platform Build Methods
188
189
Common methods available to platform implementations for build operations.
190
191
```typescript { .api }
192
/**
193
* Get current platform configuration
194
*/
195
getConfig(): T;
196
197
/**
198
* Empty the output directory with optional exclusions
199
* @param excludes - Files/patterns to exclude from deletion
200
*/
201
protected emptyOutputDir(excludes?: Array<string | RegExp>): void;
202
203
/**
204
* Get the appropriate runner for the current compiler
205
* @returns Runner function bound to app path
206
*/
207
protected getRunner(): Promise<Function>;
208
209
/**
210
* Prepare options object for runner execution
211
* @param extraOptions - Additional options to merge
212
* @returns Complete options object for runner
213
*/
214
protected getOptions(extraOptions?: any): object;
215
```
216
217
### Mini-Program Specific Methods
218
219
Additional methods available for mini-program platforms.
220
221
```typescript { .api }
222
/**
223
* Generate project configuration file for mini-program platform
224
* @param src - Source config file name in project
225
* @param dist - Target config file name in output (default: 'project.config.json')
226
*/
227
protected generateProjectConfig(src: string, dist?: string): void;
228
229
/**
230
* Recursively replace object keys using a key mapping
231
* @param obj - Object to transform
232
* @param keyMap - Mapping of old keys to new keys
233
*/
234
protected recursiveReplaceObjectKeys(obj: object, keyMap: object): void;
235
236
/**
237
* Print development tips specific to mini-program platforms
238
* @param platform - Platform name for tip customization
239
*/
240
protected printDevelopmentTip(platform: string): void;
241
```
242
243
### Platform Registration
244
245
Platforms are registered through the plugin system and made available for command execution.
246
247
```typescript { .api }
248
// In a plugin
249
ctx.registerPlatform({
250
name: 'my-platform',
251
useConfigName: 'mini', // Optional: config section to use
252
fn: (opts) => {
253
const platform = new MyCustomPlatform(ctx, opts.config);
254
return platform.start();
255
}
256
});
257
```
258
259
## Platform Implementation Examples
260
261
### Complete Mini-Program Platform
262
263
```typescript
264
import {
265
TaroPlatformBase,
266
PLATFORM_TYPE,
267
type IPluginContext,
268
type TConfig
269
} from "@tarojs/service";
270
271
class AlipayPlatform extends TaroPlatformBase {
272
platform = 'alipay';
273
globalObject = 'my';
274
projectConfigJson = 'mini.project.json';
275
276
fileType = {
277
templ: '.axml',
278
style: '.acss',
279
script: '.js',
280
config: '.json'
281
};
282
283
template = new RecursiveTemplate();
284
runtimePath = '@tarojs/runtime';
285
286
constructor(ctx: IPluginContext, config: TConfig) {
287
super(ctx, config);
288
289
// Add platform-specific setup
290
this.setupTransaction.addWrapper({
291
init: () => {
292
console.log('Initializing Alipay platform...');
293
}
294
});
295
}
296
}
297
```
298
299
### Complete Web Platform
300
301
```typescript
302
import {
303
TaroPlatformWeb,
304
type IPluginContext,
305
type TConfig
306
} from "@tarojs/service";
307
308
class ReactNativePlatform extends TaroPlatformWeb {
309
platform = 'rn';
310
runtimePath = '@tarojs/runtime-rn';
311
312
protected getOptions(extraOptions = {}) {
313
const options = super.getOptions(extraOptions);
314
315
// Add React Native specific options
316
return {
317
...options,
318
platformType: 'rn',
319
target: 'react-native',
320
...extraOptions
321
};
322
}
323
}
324
```
325
326
## Types
327
328
```typescript { .api }
329
type TConfig = Record<string, any>;
330
331
interface RecursiveTemplate {
332
// Template engine interface for recursive templates
333
}
334
335
interface UnRecursiveTemplate {
336
// Template engine interface for non-recursive templates
337
}
338
339
type Func = (...args: any[]) => any;
340
```