or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli-interface.mdindex.mdplugin-system.mdprogrammatic-api.md

programmatic-api.mddocs/

0

# Programmatic API

1

2

The WebpackCLI class provides complete programmatic access to webpack CLI functionality, allowing integration of webpack operations into custom Node.js applications and tooling.

3

4

## Capabilities

5

6

### WebpackCLI Class

7

8

Main class implementing the IWebpackCLI interface for programmatic webpack operations.

9

10

```typescript { .api }

11

class WebpackCLI implements IWebpackCLI {

12

// Properties

13

colors: WebpackCLIColors;

14

logger: WebpackCLILogger;

15

isColorSupportChanged: boolean | undefined;

16

webpack: typeof webpack;

17

builtInOptionsCache: WebpackCLIBuiltInOption[] | undefined;

18

program: WebpackCLICommand;

19

20

// Constructor

21

constructor();

22

}

23

```

24

25

**Usage Example:**

26

27

```typescript

28

import CLI from "webpack-cli";

29

30

const cli = CLI;

31

await cli.run(["--mode", "production"]);

32

```

33

34

### Core Execution Methods

35

36

Primary methods for running webpack operations programmatically.

37

38

```typescript { .api }

39

/**

40

* Main execution method - runs CLI with provided arguments

41

* @param args - Command line arguments array

42

* @param parseOptions - Optional parsing configuration

43

*/

44

run(args: string[], parseOptions?: ParseOptions): Promise<void>;

45

46

/**

47

* Run webpack compilation with options

48

* @param options - Webpack run options

49

* @param isWatchCommand - Whether this is a watch command

50

*/

51

runWebpack(options: WebpackRunOptions, isWatchCommand: boolean): Promise<void>;

52

```

53

54

**Usage Examples:**

55

56

```typescript

57

// Basic build

58

await cli.run(["./src/index.js", "--mode", "production"]);

59

60

// With custom options

61

await cli.run(["--config", "webpack.prod.js"], {

62

from: "user"

63

});

64

65

// Direct webpack execution

66

await cli.runWebpack({

67

config: webpackConfig,

68

stats: true

69

}, false);

70

```

71

72

### Configuration Management

73

74

Methods for loading, validating, and building webpack configurations.

75

76

```typescript { .api }

77

/**

78

* Load webpack configuration from files

79

* @param options - Configuration loading options

80

* @returns Promise resolving to WebpackCLIConfig

81

*/

82

loadConfig(options: Partial<WebpackDevServerOptions>): Promise<WebpackCLIConfig>;

83

84

/**

85

* Build and process configuration with CLI options

86

* @param config - Base configuration

87

* @param options - CLI options to merge

88

* @returns Promise resolving to processed config

89

*/

90

buildConfig(config: WebpackCLIConfig, options: WebpackDevServerOptions): Promise<WebpackCLIConfig>;

91

```

92

93

**Usage Examples:**

94

95

```typescript

96

// Load configuration

97

const config = await cli.loadConfig({

98

config: ["webpack.config.js"],

99

mode: "production"

100

});

101

102

// Build configuration with options

103

const builtConfig = await cli.buildConfig(config, {

104

mode: "production",

105

watch: false,

106

entry: "./src/index.js"

107

});

108

```

109

110

### Webpack Integration

111

112

Methods for webpack loading and compiler creation.

113

114

```typescript { .api }

115

/**

116

* Load webpack module dynamically

117

* @param handleError - Whether to handle loading errors

118

* @returns Promise resolving to webpack module

119

*/

120

loadWebpack(handleError?: boolean): Promise<typeof webpack>;

121

122

/**

123

* Create webpack compiler instance

124

* @param options - Compiler creation options

125

* @param callback - Optional compilation callback

126

* @returns Promise resolving to Compiler or MultiCompiler

127

*/

128

createCompiler(

129

options: Partial<WebpackDevServerOptions>,

130

callback?: Callback<[Error | undefined, Stats | MultiStats | undefined]>

131

): Promise<WebpackCompiler>;

132

```

133

134

**Usage Examples:**

135

136

```typescript

137

// Load webpack

138

const webpack = await cli.loadWebpack();

139

140

// Create compiler

141

const compiler = await cli.createCompiler({

142

config: ["webpack.config.js"],

143

mode: "development"

144

});

145

146

// Create compiler with callback

147

const compiler = await cli.createCompiler({

148

config: ["webpack.config.js"]

149

}, (err, stats) => {

150

if (err) console.error(err);

151

console.log(stats?.toString());

152

});

153

```

154

155

### Package Management

156

157

Methods for package installation and management.

158

159

```typescript { .api }

160

/**

161

* Check if a package exists in node_modules

162

* @param packageName - Name of package to check

163

* @returns Boolean indicating if package exists

164

*/

165

checkPackageExists(packageName: string): boolean;

166

167

/**

168

* Get available package managers on the system

169

* @returns Array of available package managers

170

*/

171

getAvailablePackageManagers(): PackageManager[];

172

173

/**

174

* Get the default package manager

175

* @returns Default package manager or undefined

176

*/

177

getDefaultPackageManager(): PackageManager | undefined;

178

179

/**

180

* Install a package using available package manager

181

* @param packageName - Package to install

182

* @param options - Installation options

183

* @returns Promise resolving to installation output

184

*/

185

doInstall(packageName: string, options?: PackageInstallOptions): Promise<string>;

186

```

187

188

**Usage Examples:**

189

190

```typescript

191

// Check package

192

const hasWebpack = cli.checkPackageExists("webpack");

193

194

// Get package managers

195

const managers = cli.getAvailablePackageManagers();

196

const defaultPM = cli.getDefaultPackageManager();

197

198

// Install package

199

await cli.doInstall("webpack-dev-server", {

200

packageManager: "npm"

201

});

202

```

203

204

### File and Module Operations

205

206

Utilities for loading JSON files and modules.

207

208

```typescript { .api }

209

/**

210

* Load JSON file synchronously

211

* @param path - Path to JSON file

212

* @param handleError - Whether to handle loading errors

213

* @returns Parsed JSON object

214

*/

215

loadJSONFile<T = unknown>(path: string, handleError: boolean): T;

216

217

/**

218

* Try to load a module using require then import

219

* @param module - Module name to load

220

* @param handleError - Whether to handle loading errors

221

* @param moduleType - Type of module loading to attempt

222

* @returns Promise resolving to loaded module

223

*/

224

tryRequireThenImport<T = unknown>(

225

module: string,

226

handleError: boolean,

227

moduleType?: "unknown" | "commonjs" | "esm"

228

): Promise<T>;

229

```

230

231

**Usage Examples:**

232

233

```typescript

234

// Load JSON configuration (synchronous)

235

const packageJson = cli.loadJSONFile<PackageJSON>("./package.json", true);

236

237

// Load module with module type

238

const plugin = await cli.tryRequireThenImport("webpack-bundle-analyzer", false, "unknown");

239

240

// Load ESM module specifically

241

const esmModule = await cli.tryRequireThenImport("./config.mjs", false, "esm");

242

```

243

244

### Command and Option Management

245

246

Methods for creating commands and managing CLI options.

247

248

```typescript { .api }

249

/**

250

* Create a CLI command

251

* @param commandOptions - Command configuration

252

* @param options - CLI command options

253

* @param action - Command action function

254

* @returns Promise resolving to WebpackCLICommand or undefined

255

*/

256

makeCommand(

257

commandOptions: WebpackCLIOptions,

258

options: WebpackCLICommandOptions,

259

action: CommandAction

260

): Promise<WebpackCLICommand | undefined>;

261

262

/**

263

* Add option to a command

264

* @param command - Target command

265

* @param option - Option to add

266

*/

267

makeOption(command: WebpackCLICommand, option: WebpackCLIBuiltInOption): void;

268

269

/**

270

* Get all built-in CLI options

271

* @returns Array of built-in options

272

*/

273

getBuiltInOptions(): WebpackCLIBuiltInOption[];

274

```

275

276

### Info Command Integration

277

278

Methods for system information output.

279

280

```typescript { .api }

281

/**

282

* Get info command options

283

* @returns Array of info command options

284

*/

285

getInfoOptions(): WebpackCLIBuiltInOption[];

286

287

/**

288

* Get formatted info output

289

* @param options - Info output options

290

* @returns Promise resolving to formatted info string

291

*/

292

getInfoOutput(options: {

293

output: string;

294

additionalPackage: string[]

295

}): Promise<string>;

296

```

297

298

**Usage Examples:**

299

300

```typescript

301

// Get system info

302

const infoOutput = await cli.getInfoOutput({

303

output: "json",

304

additionalPackage: ["react", "webpack-dev-server"]

305

});

306

307

console.log(infoOutput);

308

```

309

310

### Utility Methods

311

312

Helper methods for string formatting and type checking.

313

314

```typescript { .api }

315

/**

316

* Type guard to check if compiler is a MultiCompiler

317

* @param compiler - Webpack compiler instance

318

* @returns True if compiler is MultiCompiler

319

*/

320

isMultipleCompiler(compiler: WebpackCompiler): compiler is MultiCompiler;

321

322

/**

323

* Type guard to check if value is a Promise

324

* @param value - Value to check

325

* @returns True if value is a Promise

326

*/

327

isPromise<T>(value: Promise<T>): value is Promise<T>;

328

329

/**

330

* Type guard to check if value is a function

331

* @param value - Value to check

332

* @returns True if value is a function

333

*/

334

isFunction(value: unknown): value is CallableFunction;

335

336

/**

337

* Type guard to check if error is a webpack validation error

338

* @param error - Error to check

339

* @returns True if error is WebpackError

340

*/

341

isValidationError(error: Error): error is WebpackError;

342

343

/**

344

* Convert string to kebab-case

345

* @param str - String to convert

346

* @returns Kebab-case string

347

*/

348

toKebabCase(str: string): string;

349

350

/**

351

* Capitalize first letter of string

352

* @param str - String to capitalize

353

* @returns String with first letter capitalized

354

*/

355

capitalizeFirstLetter(str: string): string;

356

357

/**

358

* Get CLI logger instance

359

* @returns WebpackCLI logger

360

*/

361

getLogger(): WebpackCLILogger;

362

363

/**

364

* Create colors utility with optional color support override

365

* @param useColors - Force color support on/off

366

* @returns Colors utility instance

367

*/

368

createColors(useColors?: boolean): WebpackCLIColors;

369

370

/**

371

* Check if compiler needs stdin watching

372

* @param compiler - Webpack compiler instance

373

* @returns True if stdin watching is needed

374

*/

375

needWatchStdin(compiler: Compiler | MultiCompiler): boolean;

376

```

377

378

## Types

379

380

```typescript { .api }

381

interface WebpackCLIConfig {

382

options: WebpackConfiguration | WebpackConfiguration[];

383

path: WeakMap<object, string[]>;

384

}

385

386

interface WebpackRunOptions extends WebpackOptionsNormalized {

387

progress?: boolean | "profile";

388

json?: boolean;

389

argv?: Argv;

390

env: Env;

391

failOnWarnings?: boolean;

392

isWatchingLikeCommand?: boolean;

393

}

394

395

interface WebpackDevServerOptions extends DevServerConfig, WebpackConfiguration, ClientConfiguration, AssetEmittedInfo, WebpackOptionsNormalized, FileCacheOptions, Argv {

396

nodeEnv?: string;

397

watchOptionsStdin?: boolean;

398

progress?: boolean | "profile" | undefined;

399

analyze?: boolean;

400

prefetch?: string;

401

json?: boolean;

402

entry: EntryOptions;

403

merge?: boolean;

404

config: string[];

405

configName?: string[];

406

disableInterpret?: boolean;

407

extends?: string[];

408

argv: Argv;

409

}

410

411

interface PackageInstallOptions {

412

preMessage?: () => void;

413

}

414

415

interface WebpackCLIBuiltInOption extends WebpackCLIBuiltInFlag {

416

hidden?: boolean;

417

group?: "core";

418

}

419

420

interface WebpackCLIBuiltInFlag {

421

name: string;

422

alias?: string;

423

type?: (

424

value: string,

425

previous: Record<string, BasicPrimitive | object>,

426

) => Record<string, BasicPrimitive | object>;

427

configs?: Partial<FlagConfig>[];

428

negative?: boolean;

429

multiple?: boolean;

430

valueName?: string;

431

description?: string;

432

describe?: string;

433

negatedDescription?: string;

434

defaultValue?: string;

435

helpLevel: "minimum" | "verbose";

436

}

437

438

type PackageManager = "pnpm" | "yarn" | "npm";

439

type WebpackCompiler = Compiler | MultiCompiler;

440

type StringFormatter = (str: string) => string;

441

type CommandAction = (...args: any[]) => Promise<void> | void;

442

type BasicPrimitive = string | boolean | number;

443

type Callback<T extends unknown[]> = (...args: T) => void;

444

445

interface FlagConfig {

446

negatedDescription: string;

447

type: FlagType;

448

values: FlagType[];

449

}

450

451

type FlagType = boolean | "enum" | "string" | "path" | "number" | "boolean" | "RegExp" | "reset";

452

453

interface Env {

454

WEBPACK_BUNDLE?: boolean;

455

WEBPACK_BUILD?: boolean;

456

WEBPACK_WATCH?: boolean;

457

WEBPACK_SERVE?: boolean;

458

WEBPACK_PACKAGE?: string;

459

WEBPACK_DEV_SERVER_PACKAGE?: string;

460

}

461

462

interface Argv extends Record<string, any> {

463

env?: Env;

464

}

465

```