or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdindex.mdinternationalization.mdplugin-development.mdui-components.md

plugin-development.mddocs/

0

# Plugin Development

1

2

Core plugin development interface providing system-level APIs, tool utilities, event handlers, and application modification methods for Umi plugin development.

3

4

## Capabilities

5

6

### Main Plugin API Interface

7

8

The primary interface for Umi plugin development, providing access to all system capabilities.

9

10

```typescript { .api }

11

/**

12

* Main plugin API interface providing comprehensive access to Umi's plugin system

13

*/

14

interface IApi {

15

// System level variables

16

API_TYPE: typeof API_TYPE;

17

config: IConfig;

18

cwd: string;

19

pkg: IPkg;

20

webpackConfig: IWebpack.Configuration;

21

service: any;

22

locale: any;

23

paths: {

24

cwd: string;

25

outputPath: string;

26

absOutputPath: string;

27

absNodeModulesPath: string;

28

pagesPath: string;

29

absPagesPath: string;

30

absSrcPath: string;

31

tmpDirPath: string;

32

absTmpDirPath: string;

33

};

34

routes: IRoute[];

35

36

// System level API

37

register: IRegister;

38

registerPlugin: IRegisterPlugin;

39

registerMethod: IRegisterMethod;

40

applyPlugins: IApplyPlugins;

41

restart: IReDo<string>;

42

rebuildTmpFiles: IReDo<string>;

43

refreshBrowser: IReDo<void>;

44

rebuildHTML: IReDo<void>;

45

changePluginOption: IChangePluginOption;

46

registerCommand: IRegisterCommand;

47

_registerConfig: IRegisterConfig;

48

_modifyCommand: IModifyCommand;

49

_modifyHelpInfo: IModify<IModifyHelpInfoOpts>;

50

51

// Tool class API

52

log: { [key in DefaultMethods]: ILog<any> };

53

_: typeof lodash;

54

winPath: IWinPath;

55

relativeToTmp: IRelativeToTmp;

56

debug: ILog;

57

writeTmpFile: IWriteTmpFile;

58

getRoutes: IGetRoutes;

59

getRouteComponents: IGetRouteComponents;

60

findJS: IFind;

61

findCSS: IFind;

62

compatDirname: ICompatDirname;

63

UmiError: any;

64

65

// Event class API

66

beforeDevServer: IBeforeDevServer;

67

_beforeDevServerAsync: IBeforeDevServerAsync;

68

afterDevServer: IAfterDevServer;

69

beforeBlockWriting: IBeforeBlockWriting;

70

onStart: IOnStart;

71

onPrintUmiError: onPrintUmiError;

72

onStartAsync: IEventAsync;

73

onDevCompileDone: IOnDevCompileDone;

74

onOptionChange: IOnOptionChange;

75

onBuildSuccess: IOnBuildSuccess;

76

onBuildSuccessAsync: IOnBuildSuccessAsync;

77

onBuildFail: IOnBuildFail;

78

onHTMLRebuild: IOnHTMLRebuild;

79

onGenerateFiles: IOnGenerateFiles;

80

onPatchRoute: IOnPatchRoute;

81

onUISocket: IOnUISocket;

82

onRouteChange: (callback: () => void) => void;

83

84

// Application class API

85

modifyDefaultConfig: IModify<object>;

86

addUmiExports: IAdd<object>;

87

addPageWatcher: IAdd<string>;

88

addHTMLMeta: IAdd<object, { route?: IRoute }>;

89

addHTMLLink: IAdd<object, { route?: IRoute }>;

90

addHTMLStyle: IAdd<object, { route?: IRoute }>;

91

addHTMLScript: IAdd<object, { route?: IRoute }>;

92

addHTMLHeadScript: IAdd<object, { route?: IRoute }>;

93

modifyHTMLChunks: IModify<string[], { route?: IRoute }>;

94

modifyHTMLWithAST: IModifyHTMLWithAST;

95

modifyHTMLContext: IModify<object, { route?: IRoute }>;

96

modifyPublicPathStr: IModify<string>;

97

modifyRoutes: IModify<IRoute[]>;

98

addEntryImportAhead: IAdd<IAddImportOpts>;

99

addEntryPolyfillImports: IAdd<IAddImportOpts>;

100

addEntryImport: IAdd<IAddImportOpts>;

101

addEntryCodeAhead: IAdd<string>;

102

addEntryCode: IAdd<string>;

103

addUIPlugin: IAdd<string>;

104

addRouterImport: IAdd<IAddImportOpts>;

105

addRouterImportAhead: IAdd<IAddImportOpts>;

106

addRendererWrapperWithComponent: IAdd<string, () => string>;

107

addRendererWrapperWithModule: IAdd<string>;

108

modifyEntryRender: IModify<string>;

109

modifyEntryHistory: IModify<string>;

110

modifyRouteComponent: IModify<string, IModifyRouteComponentArgs>;

111

modifyRouterRootComponent: IModify<string>;

112

modifyWebpackConfig: IModify<IWebpack.Configuration>;

113

modifyAFWebpackOpts: IModify<IAFWebpackConfig>;

114

chainWebpackConfig: IChangeWebpackConfig<IWebpackChainConfig, IAFWebpackConfig>;

115

addMiddleware: IAdd<IMiddlewareFunction>;

116

addMiddlewareAhead: IAdd<IMiddlewareFunction>;

117

addMiddlewareBeforeMock: IAdd<IMiddlewareFunction>;

118

addMiddlewareAfterMock: IAdd<IMiddlewareFunction>;

119

addVersionInfo: IAdd<string>;

120

addRuntimePlugin: IAdd<string>;

121

addRuntimePluginKey: IAdd<string>;

122

addBlockUIResource: IAdd<object>;

123

modifyBlockUIResources: IModify<object[]>;

124

_modifyBlockPackageJSONPath: IModify<string>;

125

_modifyBlockDependencies: IModify<IBlockDependencies>;

126

_modifyBlockFile: IModify<string, IModifyBlockFileArgs>;

127

_modifyBlockTarget: IModify<string, IModifyBlockTargetArgs>;

128

_modifyBlockNewRouteConfig: IModify<any>;

129

}

130

```

131

132

**Usage Examples:**

133

134

```typescript

135

import { IApi } from 'umi-types';

136

137

export default function(api: IApi) {

138

// Access system information

139

console.log('Current working directory:', api.cwd);

140

console.log('Output path:', api.paths.absOutputPath);

141

console.log('Routes:', api.getRoutes());

142

143

// Register a command

144

api.registerCommand('build-custom', {

145

description: 'Build with custom settings',

146

usage: 'umi build-custom [options]',

147

webpack: true,

148

}, (args) => {

149

api.log.info('Building with custom settings...');

150

// Custom build logic

151

});

152

153

// Modify webpack configuration

154

api.modifyWebpackConfig((config) => {

155

config.resolve.alias = {

156

...config.resolve.alias,

157

'@components': api.winPath(`${api.paths.absSrcPath}/components`),

158

};

159

return config;

160

});

161

162

// Add HTML modifications

163

api.modifyHTMLWithAST(($, { route, getChunkPath }) => {

164

if (route.path === '/') {

165

$('head').append('<meta name="home-page" content="true">');

166

}

167

});

168

}

169

```

170

171

### System Level API

172

173

Core system-level plugin registration and method management.

174

175

```typescript { .api }

176

/**

177

* Register a hook handler for a specific hook

178

* @param hook - Hook name to listen for

179

* @param handler - Function to handle the hook

180

*/

181

interface IRegister {

182

(hook: string, handler: Function): void;

183

}

184

185

/**

186

* Register a plugin with the system

187

* @param plugin - Plugin registration options

188

*/

189

interface IRegisterPlugin {

190

(plugin: IRegisterPluginOpts): void;

191

}

192

193

interface IRegisterPluginOpts {

194

id: string;

195

apply: any;

196

opts?: object;

197

}

198

199

/**

200

* Register a new plugin method

201

* @param methodName - Name of the method to register

202

* @param opts - Method registration options

203

*/

204

interface IRegisterMethod {

205

(methodName: string, opts: IRegisterMethodOpts): void;

206

}

207

208

interface IRegisterMethodOpts {

209

type?: API_TYPE;

210

apply?: IPluginMethod;

211

}

212

213

/**

214

* Apply all registered plugins for a method

215

* @param methodName - Method name to apply plugins for

216

* @param opts - Options for plugin application

217

*/

218

interface IApplyPlugins {

219

(methodName: string, opts?: IApplyPluginsOpts): any[] | undefined | any;

220

}

221

222

interface IApplyPluginsOpts {

223

args?: any;

224

initialValue?: any;

225

}

226

227

/**

228

* Register a CLI command

229

* @param commandName - Name of the command

230

* @param opts - Command options or handler function

231

* @param fn - Command handler function (when opts provided)

232

*/

233

interface IRegisterCommand {

234

(commandName: string, opts: ICommandOpts, fn: (args: any) => any): void;

235

(commandName: string, fn: (args: any) => any): void;

236

}

237

238

interface ICommandOpts {

239

description?: string;

240

details?: string;

241

hide?: boolean;

242

options?: object;

243

usage?: string;

244

webpack?: boolean;

245

}

246

```

247

248

### Tool Class API

249

250

Utility functions and file system operations for plugin development.

251

252

```typescript { .api }

253

/**

254

* Logging interface with different log levels

255

*/

256

interface ILog<T = string> {

257

(message: T, ...messages: string[]): void;

258

}

259

260

/**

261

* Write a temporary file to the temp directory

262

* @param file - Relative file path

263

* @param content - File content

264

*/

265

interface IWriteTmpFile {

266

(file: string, content: string): void;

267

}

268

269

/**

270

* Get current route configuration

271

* @returns Array of route objects

272

*/

273

interface IGetRoutes {

274

(): IRoute[];

275

}

276

277

/**

278

* Get route component paths

279

* @returns Array of component file paths

280

*/

281

interface IGetRouteComponents {

282

(): string[];

283

}

284

285

/**

286

* Convert path to Windows-compatible format

287

* @param path - File path to convert

288

* @returns Windows-compatible path

289

*/

290

interface IWinPath {

291

(path: string): string;

292

}

293

294

/**

295

* Make path relative to temp directory

296

* @param path - Absolute path

297

* @returns Path relative to temp directory

298

*/

299

type IRelativeToTmp = (path: string) => string;

300

301

/**

302

* Find JavaScript file in directory

303

* @param baseDir - Directory to search in

304

* @param fileNameWithoutExtname - File name without extension

305

* @returns File path or null if not found

306

*/

307

interface IFind {

308

(baseDir: string, fileNameWithoutExtname?: string): string | null;

309

}

310

311

/**

312

* Get compatible directory name

313

* @param path - Path to process

314

* @param cwd - Current working directory

315

* @param fallback - Fallback value

316

* @returns Compatible directory name or fallback

317

*/

318

interface ICompatDirname<T = any> {

319

(path: string, cwd: string, fallback?: T): T | string;

320

}

321

```

322

323

### Event Handlers

324

325

Event system for plugin lifecycle management.

326

327

```typescript { .api }

328

/**

329

* Before dev server start event handler

330

* @param fn - Event handler function

331

*/

332

interface IBeforeDevServer {

333

(fn: IBeforeDevServerFunc): void;

334

}

335

336

interface IBeforeDevServerFunc {

337

(args: { server: any }): void;

338

}

339

340

/**

341

* After dev server start event handler

342

* @param fn - Event handler function

343

*/

344

interface IAfterDevServer {

345

(fn: IAfterDevServerFunc): void;

346

}

347

348

interface IAfterDevServerFunc {

349

(args: { server: any; devServerPort: number }): void;

350

}

351

352

/**

353

* On dev compilation complete event handler

354

* @param fn - Event handler function

355

*/

356

interface IOnDevCompileDone {

357

(fn: IOnDevCompileDoneFunc): void;

358

}

359

360

interface IOnDevCompileDoneFunc {

361

(args: { isFirstCompile: boolean; stats: IWebpack.Stats }): void;

362

}

363

364

/**

365

* On build success event handler

366

* @param fn - Event handler function

367

*/

368

interface IOnBuildSuccess {

369

(fn: IOnBuildSuccessFunc): void;

370

}

371

372

interface IOnBuildSuccessFunc {

373

(args: { stats: IWebpack.Stats[] }): void;

374

}

375

376

/**

377

* On build failure event handler

378

* @param fn - Event handler function

379

*/

380

interface IOnBuildFail {

381

(fn: IOnBuildFailFunc): void;

382

}

383

384

interface IOnBuildFailFunc {

385

(args: { stats: IWebpack.Stats[]; err: Error }): void;

386

}

387

388

/**

389

* On option change event handler

390

* @param fn - Event handler function

391

*/

392

interface IOnOptionChange {

393

(fn: IOnOptionChangeFunc): void;

394

}

395

396

interface IOnOptionChangeFunc<T = any> {

397

(newOpts: T): void;

398

}

399

400

/**

401

* On generate files event handler

402

* @param fn - Event handler function

403

*/

404

interface IOnGenerateFiles {

405

(fn: IOnGenerateFilesFunc): void;

406

}

407

408

interface IOnGenerateFilesFunc {

409

(args: { isRebuild?: boolean }): void;

410

}

411

412

/**

413

* On patch route event handler

414

* @param fn - Event handler function

415

*/

416

interface IOnPatchRoute {

417

(fn: IOnPatchRouteFunc): void;

418

}

419

420

interface IOnPatchRouteFunc {

421

(args: { route: IRoute }): void;

422

}

423

```

424

425

### Application Modification API

426

427

Methods for modifying Umi's runtime behavior and generated files.

428

429

```typescript { .api }

430

/**

431

* Generic modify function for plugin methods

432

* @param memo - Current value to modify

433

* @param args - Additional arguments

434

* @returns Modified value

435

*/

436

interface IModifyFunc<T, U> {

437

(memo: T, args: U): T | T;

438

}

439

440

interface IModify<T, U = {}> {

441

(fn: IModifyFunc<T, U> | T): void;

442

}

443

444

/**

445

* Generic add function for plugin methods

446

* @param memo - Current array to add to

447

* @param args - Additional arguments

448

* @returns Item or array of items to add

449

*/

450

interface IAddFunc<T, U> {

451

(memo: T[], args: U): T | T[];

452

}

453

454

interface IAdd<T, U = {}> {

455

(fn: IAddFunc<T, U> | T | T[]): void;

456

}

457

458

/**

459

* Modify HTML using CheerioJS AST

460

* @param fn - HTML modification function

461

*/

462

interface IModifyHTMLWithAST {

463

(fn: IModifyHTMLWithASTFunc): void;

464

}

465

466

interface IModifyHTMLWithASTFunc {

467

($: CheerioStatic, args: IModifyHTMLWithASTArgs): CheerioStatic;

468

}

469

470

interface IModifyHTMLWithASTArgs {

471

route: IRoute;

472

getChunkPath: IGetChunkPath;

473

}

474

475

interface IGetChunkPath {

476

(fileName: string): string | null;

477

}

478

479

/**

480

* Add import statement options

481

*/

482

interface IAddImportOpts {

483

source: string;

484

specifier?: string;

485

}

486

487

/**

488

* Middleware function for express-like middleware

489

*/

490

interface IMiddlewareFunction {

491

(req: any, res: any, next: any): void;

492

}

493

```