0
# Plugin System & Kernel
1
2
Core orchestration system managing plugins, commands, platforms, and the complete build process through an event-driven architecture with comprehensive lifecycle hooks.
3
4
## Capabilities
5
6
### Kernel Class
7
8
Central orchestrator that manages the entire plugin system, commands, platforms, and build process lifecycle.
9
10
```typescript { .api }
11
/**
12
* Core kernel class extending EventEmitter for plugin orchestration
13
*/
14
class Kernel extends EventEmitter {
15
appPath: string;
16
plugins: Map<string, IPlugin>;
17
platforms: Map<string, IPlatform>;
18
commands: Map<string, ICommand>;
19
hooks: Map<string, IHook[]>;
20
methods: Map<string, Func[]>;
21
paths: IPaths;
22
config: Config;
23
initialConfig: IProjectConfig;
24
helper: any;
25
runnerUtils: any;
26
runOpts: any;
27
28
constructor(options: IKernelOptions);
29
run(args: string | { name: string; opts?: any }): Promise<void>;
30
applyPlugins(args: string | { name: string; initialVal?: any; opts?: any }): Promise<any>;
31
runWithPlatform(platform: string): TConfig;
32
setRunOpts(opts: any): void;
33
runHelp(name: string): void;
34
}
35
36
interface IKernelOptions {
37
/** Application root path */
38
appPath: string;
39
/** Configuration instance */
40
config: Config;
41
/** List of presets to load */
42
presets?: PluginItem[];
43
/** List of plugins to load */
44
plugins?: PluginItem[];
45
}
46
```
47
48
**Usage Examples:**
49
50
```typescript
51
import { Kernel, Config } from "@tarojs/service";
52
53
// Create kernel with configuration
54
const config = new Config({ appPath: process.cwd() });
55
await config.init({ mode: 'development', command: 'build' });
56
57
const kernel = new Kernel({
58
appPath: process.cwd(),
59
config,
60
plugins: [
61
'@tarojs/plugin-react',
62
['@tarojs/plugin-sass', { /* options */ }]
63
]
64
});
65
66
// Run a build command
67
await kernel.run({
68
name: 'build',
69
opts: {
70
platform: 'weapp',
71
watch: true
72
}
73
});
74
```
75
76
### Command Execution
77
78
Execute registered commands with platform-specific configuration and options.
79
80
```typescript { .api }
81
/**
82
* Execute a registered command with optional configuration
83
* @param args - Command name or object with name and options
84
*/
85
run(args: string | { name: string; opts?: any }): Promise<void>;
86
```
87
88
The `run` method orchestrates the complete command lifecycle:
89
1. Initializes all presets and plugins
90
2. Applies `onReady` and `onStart` hooks
91
3. Validates command exists
92
4. Configures platform-specific settings if specified
93
5. Executes the command through plugin hooks
94
95
**Usage Examples:**
96
97
```typescript
98
// Simple command execution
99
await kernel.run('build');
100
101
// Command with options
102
await kernel.run({
103
name: 'build',
104
opts: {
105
platform: 'weapp',
106
watch: true,
107
options: { port: 3000 }
108
}
109
});
110
```
111
112
### Hook System
113
114
Execute registered hooks with waterfall pattern for data transformation and event handling.
115
116
```typescript { .api }
117
/**
118
* Apply registered hooks in waterfall pattern
119
* @param args - Hook name or object with name, initial value, and options
120
* @returns Promise resolving to final transformed value
121
*/
122
applyPlugins(args: string | { name: string; initialVal?: any; opts?: any }): Promise<any>;
123
```
124
125
Hook execution supports three patterns:
126
- **Modify hooks** (`modifyWebpackChain`, `modifyViteConfig`): Transform and return values
127
- **Event hooks** (`onBuildStart`, `onBuildFinish`): Execute side effects
128
- **Add hooks** (`addPluginOptsSchema`): Collect multiple values into array
129
130
**Usage Examples:**
131
132
```typescript
133
// Execute event hook
134
await kernel.applyPlugins('onBuildStart');
135
136
// Execute modify hook with initial value
137
const modifiedConfig = await kernel.applyPlugins({
138
name: 'modifyWebpackChain',
139
initialVal: webpackConfig,
140
opts: { data: buildData }
141
});
142
```
143
144
### Platform Configuration
145
146
Configure and execute builds with platform-specific settings.
147
148
```typescript { .api }
149
/**
150
* Configure kernel for specific platform execution
151
* @param platform - Platform name to configure for
152
* @returns Platform-specific configuration object
153
*/
154
runWithPlatform(platform: string): TConfig;
155
```
156
157
Configures the kernel with platform-specific settings and sets environment variables for the target platform.
158
159
### Plugin Class
160
161
Base plugin class providing registration capabilities for hooks, commands, platforms, and methods.
162
163
```typescript { .api }
164
/**
165
* Base plugin class for registering hooks and capabilities
166
*/
167
class Plugin {
168
id: string;
169
path: string;
170
ctx: Kernel;
171
optsSchema: Func;
172
173
constructor(opts: { id: string; path: string; ctx: Kernel });
174
register(hook: IHook): void;
175
registerCommand(command: ICommand): void;
176
registerPlatform(platform: IPlatform): void;
177
registerMethod(...args: any[]): void;
178
addPluginOptsSchema(schema: Function): void;
179
}
180
```
181
182
**Usage in Plugin Development:**
183
184
```typescript
185
// Plugin implementation
186
export default (ctx) => {
187
// Register a build hook
188
ctx.register({
189
name: 'onBuildStart',
190
fn: async (opts) => {
191
console.log('Build starting...');
192
}
193
});
194
195
// Register a webpack modification hook
196
ctx.register({
197
name: 'modifyWebpackChain',
198
fn: (opts, { chain }) => {
199
chain.plugin('MyPlugin')
200
.use(MyWebpackPlugin, [options]);
201
return { chain };
202
}
203
});
204
205
// Register a custom command
206
ctx.registerCommand({
207
name: 'custom-build',
208
fn: async (opts) => {
209
// Custom build logic
210
}
211
});
212
};
213
```
214
215
### Plugin Registration and Management
216
217
Internal methods for managing plugin lifecycle and registration.
218
219
```typescript { .api }
220
/**
221
* Initialize and register a single plugin
222
* @param plugin - Plugin configuration object
223
*/
224
initPlugin(plugin: IPlugin): void;
225
226
/**
227
* Initialize and register a preset (which can load additional plugins)
228
* @param preset - Preset configuration object
229
* @param isGlobalConfigPreset - Whether this preset is from global config
230
*/
231
initPreset(preset: IPreset, isGlobalConfigPreset?: boolean): void;
232
233
/**
234
* Register a plugin in the kernel's plugin registry
235
* @param plugin - Plugin to register
236
*/
237
registerPlugin(plugin: IPlugin): void;
238
```
239
240
## Core Plugin Interfaces
241
242
```typescript { .api }
243
interface IPlugin {
244
/** Unique plugin identifier */
245
id: string;
246
/** Plugin file path */
247
path: string;
248
/** Plugin configuration options */
249
opts: any;
250
/** Plugin type (Plugin or Preset) */
251
type: PluginType;
252
/** Plugin apply function that returns the plugin implementation */
253
apply: Func;
254
}
255
256
interface IHook {
257
/** Hook name (e.g., 'onBuildStart', 'modifyWebpackChain') */
258
name: string;
259
/** Plugin ID that registered this hook */
260
plugin?: string;
261
/** Hook implementation function */
262
fn: Func;
263
/** Execute this hook before another hook */
264
before?: string;
265
/** Execution stage (lower numbers execute first) */
266
stage?: number;
267
}
268
269
interface ICommand extends IHook {
270
/** Command alias */
271
alias?: string;
272
/** CLI options mapping for help display */
273
optionsMap?: Record<string, string>;
274
/** Usage examples for help display */
275
synopsisList?: string[];
276
}
277
278
interface IPlatform extends IHook {
279
/** Configuration section name to use for this platform */
280
useConfigName?: string;
281
}
282
283
enum PluginType {
284
Preset = 'Preset',
285
Plugin = 'Plugin'
286
}
287
```
288
289
## Plugin Development Patterns
290
291
### Basic Plugin Structure
292
293
```typescript
294
export default (ctx) => {
295
// Plugin initialization
296
ctx.register({
297
name: 'onBuildStart',
298
fn: async (opts) => {
299
// Build start logic
300
}
301
});
302
};
303
```
304
305
### Plugin with Options Validation
306
307
```typescript
308
export default (ctx, opts) => {
309
// Add options schema validation
310
ctx.addPluginOptsSchema((joi) => {
311
return joi.object({
312
outputDir: joi.string(),
313
minify: joi.boolean().default(true)
314
});
315
});
316
317
// Use validated options
318
ctx.register({
319
name: 'modifyWebpackChain',
320
fn: (opts, { chain }) => {
321
if (opts.minify) {
322
// Add minification
323
}
324
}
325
});
326
};
327
```
328
329
### Preset Structure
330
331
```typescript
332
export default (ctx, opts) => {
333
return {
334
presets: [
335
// Additional presets to load
336
],
337
plugins: [
338
// Plugins to load
339
'@tarojs/plugin-react',
340
['@tarojs/plugin-sass', { /* options */ }]
341
]
342
};
343
};
344
```