0
# Service Management
1
2
Ice.js provides programmatic access to its build and development capabilities through the service management API. This allows for custom tooling, integration with other build systems, and advanced workflow automation.
3
4
## Capabilities
5
6
### Create Service
7
8
Creates an Ice.js service instance for programmatic build and development operations.
9
10
```typescript { .api }
11
/**
12
* Create Ice.js service instance for programmatic build/dev operations
13
* @param options - Service creation options
14
* @returns Promise resolving to service instance with run method
15
*/
16
function createService(options: CreateServiceOptions): Promise<ServiceInstance>;
17
18
interface CreateServiceOptions {
19
/** Project root directory path */
20
rootDir: string;
21
/** Command to execute */
22
command: 'start' | 'build' | 'test';
23
/** Command-line arguments and options */
24
commandArgs: CommandArgs;
25
}
26
27
interface ServiceInstance {
28
/** Execute the service operation */
29
run(): Promise<any>;
30
}
31
32
interface CommandArgs {
33
/** Build/start target platform */
34
target?: 'web' | 'weex' | 'ali-miniapp' | 'wechat-miniprogram' |
35
'bytedance-microapp' | 'baidu-smartprogram' | 'kuaishou-miniprogram';
36
/** Build mode */
37
mode?: 'development' | 'production';
38
/** Configuration file path */
39
config?: string;
40
/** Development server host */
41
host?: string;
42
/** Development server port */
43
port?: number;
44
/** Enable bundle analyzer */
45
analyzer?: boolean;
46
/** Enable HTTPS */
47
https?: boolean | 'self-signed';
48
/** Force cache clear */
49
force?: boolean;
50
/** Enable speedup mode */
51
speedup?: boolean;
52
/** Browser opening behavior */
53
open?: boolean | string;
54
/** Disable browser opening */
55
'no-open'?: boolean;
56
/** Disable mock service */
57
'no-mock'?: boolean;
58
/** List available pages */
59
list?: boolean;
60
/** Custom plugin */
61
plugin?: string;
62
[key: string]: any; // Support for additional unknown options
63
}
64
```
65
66
**Usage Examples:**
67
68
```typescript
69
import createService from "@ice/app/service";
70
71
// Development server
72
const devService = await createService({
73
rootDir: process.cwd(),
74
command: 'start',
75
commandArgs: {
76
mode: 'development',
77
host: 'localhost',
78
port: 3000,
79
analyzer: false,
80
https: false
81
}
82
});
83
84
await devService.run();
85
86
// Production build
87
const buildService = await createService({
88
rootDir: '/path/to/project',
89
command: 'build',
90
commandArgs: {
91
mode: 'production',
92
target: 'web',
93
analyzer: true,
94
config: './ice.config.prod.ts'
95
}
96
});
97
98
await buildService.run();
99
```
100
101
### Programmatic Development Server
102
103
Start a development server programmatically with full configuration control.
104
105
```typescript { .api }
106
/**
107
* Start development server programmatically
108
*/
109
async function startDevServer(rootDir: string, options?: DevServerOptions): Promise<ServiceInstance>;
110
111
interface DevServerOptions {
112
host?: string;
113
port?: number;
114
https?: boolean | 'self-signed';
115
open?: boolean | string;
116
mock?: boolean;
117
target?: string;
118
config?: string;
119
analyzer?: boolean;
120
speedup?: boolean;
121
force?: boolean;
122
}
123
```
124
125
**Usage Examples:**
126
127
```typescript
128
import createService from "@ice/app/service";
129
130
// Basic development server
131
const service = await createService({
132
rootDir: __dirname,
133
command: 'start',
134
commandArgs: {
135
host: '0.0.0.0',
136
port: 8080,
137
https: true,
138
open: '/dashboard'
139
}
140
});
141
142
try {
143
await service.run();
144
console.log('Development server started successfully');
145
} catch (error) {
146
console.error('Failed to start development server:', error);
147
process.exit(1);
148
}
149
```
150
151
### Programmatic Build
152
153
Execute production builds programmatically with custom configuration.
154
155
```typescript { .api }
156
/**
157
* Execute production build programmatically
158
*/
159
async function buildProject(rootDir: string, options?: BuildOptions): Promise<ServiceInstance>;
160
161
interface BuildOptions {
162
target?: string;
163
mode?: string;
164
analyzer?: boolean;
165
config?: string;
166
plugin?: string;
167
}
168
```
169
170
**Usage Examples:**
171
172
```typescript
173
import createService from "@ice/app/service";
174
175
// Multi-platform build function
176
async function buildForPlatform(platform: string) {
177
const service = await createService({
178
rootDir: process.cwd(),
179
command: 'build',
180
commandArgs: {
181
target: platform,
182
mode: 'production',
183
analyzer: platform === 'web' // Only analyze web builds
184
}
185
});
186
187
return service.run();
188
}
189
190
// Build for multiple platforms
191
const platforms = ['web', 'ali-miniapp', 'wechat-miniprogram'];
192
193
for (const platform of platforms) {
194
console.log(`Building for ${platform}...`);
195
try {
196
await buildForPlatform(platform);
197
console.log(`✅ ${platform} build completed`);
198
} catch (error) {
199
console.error(`❌ ${platform} build failed:`, error);
200
}
201
}
202
```
203
204
### Custom Build Pipeline Integration
205
206
Integrate Ice.js service into custom build pipelines and automation tools.
207
208
```typescript { .api }
209
/**
210
* Custom build pipeline example
211
*/
212
interface BuildPipelineOptions {
213
rootDir: string;
214
platforms: string[];
215
config?: string;
216
enableAnalysis?: boolean;
217
outputBase?: string;
218
}
219
```
220
221
**Usage Examples:**
222
223
```typescript
224
import createService from "@ice/app/service";
225
import path from 'path';
226
227
class IceBuildPipeline {
228
private options: BuildPipelineOptions;
229
230
constructor(options: BuildPipelineOptions) {
231
this.options = options;
232
}
233
234
async buildAll(): Promise<void> {
235
const { platforms, rootDir, config, enableAnalysis } = this.options;
236
237
for (const platform of platforms) {
238
await this.buildPlatform(platform);
239
}
240
}
241
242
private async buildPlatform(platform: string): Promise<void> {
243
const service = await createService({
244
rootDir: this.options.rootDir,
245
command: 'build',
246
commandArgs: {
247
target: platform,
248
mode: 'production',
249
config: this.options.config,
250
analyzer: this.options.enableAnalysis && platform === 'web'
251
}
252
});
253
254
try {
255
await service.run();
256
console.log(`✅ Successfully built ${platform}`);
257
} catch (error) {
258
console.error(`❌ Failed to build ${platform}:`, error);
259
throw error;
260
}
261
}
262
}
263
264
// Usage
265
const pipeline = new IceBuildPipeline({
266
rootDir: '/path/to/project',
267
platforms: ['web', 'ali-miniapp'],
268
config: './ice.config.prod.ts',
269
enableAnalysis: true
270
});
271
272
await pipeline.buildAll();
273
```
274
275
### Development Workflow Automation
276
277
Automate development workflows with service management.
278
279
```typescript { .api }
280
/**
281
* Development workflow automation
282
*/
283
interface WorkflowOptions {
284
rootDir: string;
285
environments: Array<{
286
name: string;
287
host: string;
288
port: number;
289
target?: string;
290
config?: string;
291
}>;
292
}
293
```
294
295
**Usage Examples:**
296
297
```typescript
298
import createService from "@ice/app/service";
299
300
class DevelopmentWorkflow {
301
private options: WorkflowOptions;
302
303
constructor(options: WorkflowOptions) {
304
this.options = options;
305
}
306
307
async startEnvironment(envName: string): Promise<ServiceInstance> {
308
const env = this.options.environments.find(e => e.name === envName);
309
if (!env) {
310
throw new Error(`Environment ${envName} not found`);
311
}
312
313
const service = await createService({
314
rootDir: this.options.rootDir,
315
command: 'start',
316
commandArgs: {
317
host: env.host,
318
port: env.port,
319
target: env.target || 'web',
320
config: env.config,
321
mode: 'development'
322
}
323
});
324
325
console.log(`Starting ${envName} environment on ${env.host}:${env.port}`);
326
return service;
327
}
328
329
async startAll(): Promise<ServiceInstance[]> {
330
const services = [];
331
332
for (const env of this.options.environments) {
333
const service = await this.startEnvironment(env.name);
334
services.push(service);
335
336
// Start services sequentially to avoid port conflicts
337
await service.run();
338
}
339
340
return services;
341
}
342
}
343
344
// Usage
345
const workflow = new DevelopmentWorkflow({
346
rootDir: process.cwd(),
347
environments: [
348
{
349
name: 'web',
350
host: 'localhost',
351
port: 3000,
352
target: 'web'
353
},
354
{
355
name: 'miniapp',
356
host: 'localhost',
357
port: 3001,
358
target: 'ali-miniapp',
359
config: './ice.config.miniapp.ts'
360
}
361
]
362
});
363
364
// Start specific environment
365
const webService = await workflow.startEnvironment('web');
366
await webService.run();
367
```
368
369
### Error Handling
370
371
Handle service errors and implement retry logic.
372
373
```typescript { .api }
374
/**
375
* Service error handling utilities
376
*/
377
interface ServiceError extends Error {
378
code?: string;
379
phase?: 'initialization' | 'build' | 'serve';
380
details?: any;
381
}
382
```
383
384
**Usage Examples:**
385
386
```typescript
387
import createService from "@ice/app/service";
388
389
async function buildWithRetry(options: CreateServiceOptions, maxRetries = 3): Promise<void> {
390
let attempt = 1;
391
392
while (attempt <= maxRetries) {
393
try {
394
const service = await createService(options);
395
await service.run();
396
console.log('Build completed successfully');
397
return;
398
} catch (error) {
399
console.error(`Build attempt ${attempt} failed:`, error.message);
400
401
if (attempt === maxRetries) {
402
throw new Error(`Build failed after ${maxRetries} attempts: ${error.message}`);
403
}
404
405
// Wait before retry
406
await new Promise(resolve => setTimeout(resolve, 2000 * attempt));
407
attempt++;
408
}
409
}
410
}
411
412
// Usage with error handling
413
try {
414
await buildWithRetry({
415
rootDir: process.cwd(),
416
command: 'build',
417
commandArgs: {
418
mode: 'production',
419
target: 'web'
420
}
421
});
422
} catch (error) {
423
console.error('Final build failure:', error);
424
process.exit(1);
425
}
426
```
427
428
### Service Configuration Resolution
429
430
Understand how service configurations are resolved and merged.
431
432
```typescript { .api }
433
/**
434
* Configuration resolution order:
435
* 1. Command line arguments (highest priority)
436
* 2. Configuration file options
437
* 3. Environment variables
438
* 4. Default values (lowest priority)
439
*/
440
interface ConfigurationResolution {
441
commandArgs: CommandArgs; // Highest priority
442
configFile: UserConfig; // From ice.config.*
443
environment: NodeJS.ProcessEnv; // Environment variables
444
defaults: Record<string, any>; // Framework defaults
445
}
446
```
447
448
This service management API provides full programmatic control over Ice.js operations, enabling integration with custom build tools, CI/CD pipelines, and development workflows while maintaining the same powerful features available through the CLI.