or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

build-configuration.mdcompiler-api.mdcomponent-development.mddevelopment-server.mdindex.mdruntime-utilities.mdtesting-utilities.md

compiler-api.mddocs/

0

# Compiler API

1

2

Advanced compiler APIs for build tools, plugins, and custom integrations. The Stencil compiler provides programmatic access to compilation, file watching, and build result processing.

3

4

## Capabilities

5

6

### Compiler Interface

7

8

Main compiler interface for programmatic build operations.

9

10

```typescript { .api }

11

/**

12

* Main Stencil compiler interface

13

*/

14

interface Compiler {

15

/** Build the project once */

16

build(): Promise<CompilerBuildResults>;

17

/** Create a file watcher for continuous builds */

18

createWatcher(): Promise<CompilerWatcher>;

19

/** Destroy the compiler and clean up resources */

20

destroy(): Promise<void>;

21

/** Compiler system instance */

22

sys: CompilerSystem;

23

}

24

25

/**

26

* Results from a compiler build operation

27

*/

28

interface CompilerBuildResults {

29

/** Unique build identifier */

30

buildId: number;

31

/** Component dependency graph */

32

componentGraph?: BuildResultsComponentGraph;

33

/** Compilation diagnostics and errors */

34

diagnostics: Diagnostic[];

35

/** Directories added during build */

36

dirsAdded: string[];

37

/** Directories deleted during build */

38

dirsDeleted: string[];

39

/** Build duration in milliseconds */

40

duration: number;

41

/** Files added during build */

42

filesAdded: string[];

43

/** Files changed during build */

44

filesChanged: string[];

45

/** Files deleted during build */

46

filesDeleted: string[];

47

/** Files updated during build */

48

filesUpdated: string[];

49

/** Whether build had errors */

50

hasError: boolean;

51

/** Whether build was successful */

52

hasSuccessfulBuild: boolean;

53

/** Hot module replacement data */

54

hmr?: HotModuleReplacement;

55

/** Path to hydrate app file */

56

hydrateAppFilePath?: string;

57

/** Whether this was a rebuild */

58

isRebuild: boolean;

59

/** Project namespace */

60

namespace: string;

61

/** Build outputs generated */

62

outputs: BuildOutput[];

63

/** Root directory path */

64

rootDir: string;

65

/** Source directory path */

66

srcDir: string;

67

/** Build timestamp */

68

timestamp: string;

69

}

70

71

interface BuildResultsComponentGraph {

72

[scopeId: string]: string[];

73

}

74

75

interface BuildOutput {

76

/** Output target type */

77

type: string;

78

/** Generated files */

79

files: string[];

80

}

81

```

82

83

### Compiler Factory Function

84

85

Creates a new compiler instance with the provided configuration.

86

87

```typescript { .api }

88

/**

89

* Create a new Stencil compiler instance

90

* @param config - Stencil configuration object

91

* @returns Promise resolving to a Compiler instance

92

*/

93

function createCompiler(config: StencilConfig): Promise<Compiler>;

94

```

95

96

**Usage Examples:**

97

98

```typescript

99

import { createCompiler } from '@stencil/core/compiler';

100

101

async function buildProject() {

102

const compiler = await createCompiler({

103

// Stencil config

104

namespace: 'MyApp',

105

outputTargets: [

106

{ type: 'dist' },

107

{ type: 'www' }

108

]

109

});

110

111

try {

112

const results = await compiler.build();

113

114

console.log(`Build completed in ${results.duration}ms`);

115

console.log(`Generated ${results.outputs.length} outputs`);

116

117

if (results.hasError) {

118

console.error('Build had errors:');

119

results.diagnostics.forEach(diagnostic => {

120

console.error(diagnostic.messageText);

121

});

122

}

123

} finally {

124

await compiler.destroy();

125

}

126

}

127

```

128

129

### File Watcher

130

131

Interface for watching files and triggering rebuilds on changes.

132

133

```typescript { .api }

134

/**

135

* File watcher for continuous builds

136

*/

137

interface CompilerWatcher extends BuildOnEvents {

138

/** Start watching for file changes */

139

start: () => Promise<WatcherCloseResults>;

140

/** Stop watching and close */

141

close: () => Promise<WatcherCloseResults>;

142

/** Request specific file processing */

143

request: (data: CompilerRequest) => Promise<CompilerRequestResponse>;

144

}

145

146

interface WatcherCloseResults {

147

/** Exit code from watcher */

148

exitCode: number;

149

}

150

151

interface CompilerRequest {

152

/** File path to process */

153

path?: string;

154

}

155

156

interface CompilerRequestResponse {

157

/** Requested file path */

158

path: string;

159

/** Node module ID */

160

nodeModuleId: string;

161

/** Node module version */

162

nodeModuleVersion: string;

163

/** Resolved Node module path */

164

nodeResolvedPath: string;

165

/** Cache file path */

166

cachePath: string;

167

/** Whether result was from cache */

168

cacheHit: boolean;

169

/** File content */

170

content: string;

171

/** HTTP status code */

172

status: number;

173

}

174

```

175

176

**Usage Example:**

177

178

```typescript

179

async function watchProject() {

180

const compiler = await createCompiler(config);

181

const watcher = await compiler.createWatcher();

182

183

// Listen to build events

184

watcher.on('buildStart', (buildStart) => {

185

console.log(`Build ${buildStart.buildId} started`);

186

});

187

188

watcher.on('buildFinish', (buildResults) => {

189

console.log(`Build ${buildResults.buildId} finished in ${buildResults.duration}ms`);

190

if (buildResults.hasError) {

191

console.error('Build errors occurred');

192

}

193

});

194

195

watcher.on('buildLog', (buildLog) => {

196

console.log(`Build ${buildLog.buildId}: ${buildLog.messages.join(' ')}`);

197

});

198

199

// Start watching

200

const results = await watcher.start();

201

console.log(`Watcher exited with code ${results.exitCode}`);

202

}

203

```

204

205

### Compiler System

206

207

File system abstraction layer for compiler operations.

208

209

```typescript { .api }

210

/**

211

* Compiler system abstraction for file operations

212

*/

213

interface CompilerSystem {

214

/** System name identifier */

215

name: 'node' | 'in-memory';

216

/** System version */

217

version: string;

218

/** Build events system */

219

events?: BuildEvents;

220

/** System details */

221

details?: SystemDetails;

222

223

/** Add cleanup callback */

224

addDestroy(cb: () => void): void;

225

/** Check file/directory access */

226

access(p: string): Promise<boolean>;

227

/** Synchronous access check */

228

accessSync(p: string): boolean;

229

/** Copy file between paths */

230

copyFile(src: string, dst: string): Promise<boolean>;

231

/** Destroy system and cleanup */

232

destroy(): Promise<void>;

233

/** Create directory */

234

createDir(p: string, opts?: CompilerSystemCreateDirectoryOptions): Promise<CompilerSystemCreateDirectoryResults>;

235

/** Synchronous create directory */

236

createDirSync(p: string, opts?: CompilerSystemCreateDirectoryOptions): CompilerSystemCreateDirectoryResults;

237

/** Get home directory */

238

homeDir(): string;

239

/** Check if running in TTY */

240

isTTY(): boolean;

241

/** Encode string to base64 */

242

encodeToBase64(str: string): string;

243

/** Exit process */

244

exit(exitCode: number): Promise<void>;

245

/** Get current directory */

246

getCurrentDirectory(): string;

247

/** Get compiler executing path */

248

getCompilerExecutingPath(): string;

249

/** Get dev server executing path */

250

getDevServerExecutingPath?(): string;

251

/** Get environment variable */

252

getEnvironmentVar?(key: string): string;

253

/** Get local module path */

254

getLocalModulePath(opts: { rootDir: string; moduleId: string; path: string }): string;

255

/** Get remote module URL */

256

getRemoteModuleUrl(opts: { moduleId: string; path?: string; version?: string }): string;

257

/** Hardware concurrency (CPU cores) */

258

hardwareConcurrency: number;

259

/** Check if path is symbolic link */

260

isSymbolicLink(p: string): Promise<boolean>;

261

/** Schedule next tick callback */

262

nextTick(cb: () => void): void;

263

/** Normalize file path */

264

normalizePath(p: string): string;

265

/** Platform path utilities */

266

platformPath: PlatformPath;

267

/** Read directory contents */

268

readDir(p: string): Promise<string[]>;

269

/** Synchronous read directory */

270

readDirSync(p: string): string[];

271

/** Read file content */

272

readFile(p: string): Promise<string>;

273

readFile(p: string, encoding: 'utf8'): Promise<string>;

274

readFile(p: string, encoding: 'binary'): Promise<any>;

275

/** Synchronous read file */

276

readFileSync(p: string, encoding?: string): string;

277

/** Resolve real path */

278

realpath(p: string): Promise<CompilerSystemRealpathResults>;

279

/** Synchronous resolve real path */

280

realpathSync(p: string): CompilerSystemRealpathResults;

281

/** Remove destroy callback */

282

removeDestroy(cb: () => void): void;

283

/** Rename file/directory */

284

rename(oldPath: string, newPath: string): Promise<CompilerSystemRenameResults>;

285

/** Resolve path */

286

resolvePath(p: string): string;

287

/** Remove directory */

288

removeDir(p: string, opts?: CompilerSystemRemoveDirectoryOptions): Promise<CompilerSystemRemoveDirectoryResults>;

289

/** Synchronous remove directory */

290

removeDirSync(p: string, opts?: CompilerSystemRemoveDirectoryOptions): CompilerSystemRemoveDirectoryResults;

291

/** Remove file */

292

removeFile(p: string): Promise<CompilerSystemRemoveFileResults>;

293

/** Synchronous remove file */

294

removeFileSync(p: string): CompilerSystemRemoveFileResults;

295

/** Get file/directory stats */

296

stat(p: string): Promise<CompilerFsStats>;

297

/** Synchronous get file/directory stats */

298

statSync(p: string): CompilerFsStats;

299

/** Get temporary directory */

300

tmpDirSync(): string;

301

/** Watch timeout in milliseconds */

302

watchTimeout?: number;

303

/** Write file content */

304

writeFile(p: string, content: string): Promise<CompilerSystemWriteFileResults>;

305

/** Synchronous write file */

306

writeFileSync(p: string, content: string): CompilerSystemWriteFileResults;

307

}

308

309

interface CompilerFsStats {

310

/** Whether path is a directory */

311

isDirectory: boolean;

312

/** Whether path is a file */

313

isFile: boolean;

314

/** Whether path is a symbolic link */

315

isSymbolicLink: boolean;

316

/** File size in bytes */

317

size: number;

318

/** Modified time in milliseconds */

319

mtimeMs?: number;

320

/** Error if operation failed */

321

error: any;

322

}

323

324

interface SystemDetails {

325

/** CPU model */

326

cpuModel: string;

327

/** Free memory function */

328

freemem(): number;

329

/** Platform identifier */

330

platform: 'darwin' | 'windows' | 'linux' | '';

331

/** OS release version */

332

release: string;

333

/** Total memory */

334

totalmem: number;

335

}

336

```

337

338

### Build Events

339

340

Event system for monitoring build progress and file changes.

341

342

```typescript { .api }

343

/**

344

* Build event system for monitoring compilation

345

*/

346

interface BuildEvents extends BuildOnEvents, BuildEmitEvents {

347

/** Unsubscribe all event listeners */

348

unsubscribeAll(): void;

349

}

350

351

interface BuildOnEvents {

352

/** Listen to any build event */

353

on(cb: (eventName: CompilerEventName, data: any) => void): BuildOnEventRemove;

354

/** Listen to file add events */

355

on(eventName: 'fileAdd', cb: (path: string) => void): BuildOnEventRemove;

356

/** Listen to file delete events */

357

on(eventName: 'fileDelete', cb: (path: string) => void): BuildOnEventRemove;

358

/** Listen to file update events */

359

on(eventName: 'fileUpdate', cb: (path: string) => void): BuildOnEventRemove;

360

/** Listen to directory add events */

361

on(eventName: 'dirAdd', cb: (path: string) => void): BuildOnEventRemove;

362

/** Listen to directory delete events */

363

on(eventName: 'dirDelete', cb: (path: string) => void): BuildOnEventRemove;

364

/** Listen to build start events */

365

on(eventName: 'buildStart', cb: (buildStart: CompilerBuildStart) => void): BuildOnEventRemove;

366

/** Listen to build finish events */

367

on(eventName: 'buildFinish', cb: (buildResults: CompilerBuildResults) => void): BuildOnEventRemove;

368

/** Listen to build log events */

369

on(eventName: 'buildLog', cb: (buildLog: BuildLog) => void): BuildOnEventRemove;

370

/** Listen to build no-change events */

371

on(eventName: 'buildNoChange', cb: () => void): BuildOnEventRemove;

372

}

373

374

interface BuildEmitEvents {

375

/** Emit build events */

376

emit(eventName: CompilerEventName, path: string): void;

377

emit(eventName: 'buildStart', buildStart: CompilerBuildStart): void;

378

emit(eventName: 'buildFinish', buildResults: CompilerBuildResults): void;

379

emit(eventName: 'buildNoChange', buildNoChange: BuildNoChangeResults): void;

380

emit(eventName: 'buildLog', buildLog: BuildLog): void;

381

emit(eventName: 'fsChange', fsWatchResults: FsWatchResults): void;

382

}

383

384

type BuildOnEventRemove = () => boolean;

385

386

interface CompilerBuildStart {

387

/** Build identifier */

388

buildId: number;

389

/** Build start timestamp */

390

timestamp: string;

391

}

392

393

interface BuildLog {

394

/** Build identifier */

395

buildId: number;

396

/** Log messages */

397

messages: string[];

398

/** Build progress percentage */

399

progress: number;

400

}

401

402

interface BuildNoChangeResults {

403

/** Build identifier */

404

buildId: number;

405

/** No changes detected flag */

406

noChange: boolean;

407

}

408

409

interface FsWatchResults {

410

/** Directories added */

411

dirsAdded: string[];

412

/** Directories deleted */

413

dirsDeleted: string[];

414

/** Files updated */

415

filesUpdated: string[];

416

/** Files added */

417

filesAdded: string[];

418

/** Files deleted */

419

filesDeleted: string[];

420

}

421

```

422

423

### Transpilation API

424

425

Standalone transpilation functionality for TypeScript and JSX processing.

426

427

```typescript { .api }

428

/**

429

* Transpile TypeScript/JSX code to JavaScript

430

* @param code - Source code to transpile

431

* @param opts - Transpilation options

432

* @returns Transpilation results

433

*/

434

function transpile(code: string, opts?: TranspileOptions): Promise<TranspileResults>;

435

436

interface TranspileOptions {

437

/** Component export style */

438

componentExport?: 'customelement' | 'module' | string | undefined;

439

/** Component metadata handling */

440

componentMetadata?: 'runtimestatic' | 'compilerstatic' | string | undefined;

441

/** Core import path */

442

coreImportPath?: string;

443

/** Current working directory */

444

currentDirectory?: string;

445

/** Input file name */

446

file?: string;

447

/** Module format */

448

module?: 'cjs' | 'esm' | string;

449

/** Property proxy style */

450

proxy?: 'defineproperty' | string | undefined;

451

/** Style handling */

452

style?: 'static' | string | undefined;

453

/** Style import data format */

454

styleImportData?: 'queryparams' | string | undefined;

455

/** Compilation target */

456

target?: CompileTarget;

457

/** Source map generation */

458

sourceMap?: boolean | 'inline';

459

/** Base URL for module resolution */

460

baseUrl?: string;

461

/** Path mapping for module resolution */

462

paths?: { [key: string]: string[] };

463

/** Compiler system */

464

sys?: CompilerSystem;

465

/** Transform aliased import paths */

466

transformAliasedImportPaths?: boolean;

467

}

468

469

interface TranspileResults {

470

/** Compiled JavaScript code */

471

code: string;

472

/** Additional data */

473

data?: any[];

474

/** Compilation diagnostics */

475

diagnostics: Diagnostic[];

476

/** Import statements found */

477

imports?: { path: string }[];

478

/** Input file extension */

479

inputFileExtension: string;

480

/** Input file path */

481

inputFilePath: string;

482

/** Generated source map */

483

map: any;

484

/** Output file path */

485

outputFilePath: string;

486

}

487

488

type CompileTarget =

489

| 'latest'

490

| 'esnext'

491

| 'es2020'

492

| 'es2019'

493

| 'es2018'

494

| 'es2017'

495

| 'es2015'

496

| 'es5'

497

| string

498

| undefined;

499

```

500

501

**Usage Example:**

502

503

```typescript

504

import { transpile } from '@stencil/core/compiler';

505

506

async function transpileComponent() {

507

const sourceCode = `

508

import { Component, h } from '@stencil/core';

509

510

@Component({

511

tag: 'my-component'

512

})

513

export class MyComponent {

514

render() {

515

return <div>Hello World</div>;

516

}

517

}

518

`;

519

520

const results = await transpile(sourceCode, {

521

module: 'esm',

522

target: 'es2017',

523

componentExport: 'customelement',

524

file: 'my-component.tsx'

525

});

526

527

console.log('Transpiled code:', results.code);

528

529

if (results.diagnostics.length > 0) {

530

console.log('Diagnostics:', results.diagnostics);

531

}

532

}

533

```