or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# @parcel/packager-ts

1

2

@parcel/packager-ts is a TypeScript packager plugin for Parcel that handles the final packaging phase of TypeScript compilation. It processes single-asset TypeScript bundles by extracting compiled JavaScript code, managing source maps, and appending proper source map references for debugging support.

3

4

## Package Information

5

6

- **Package Name**: @parcel/packager-ts

7

- **Package Type**: npm

8

- **Language**: JavaScript (Flow)

9

- **Installation**: Automatically installed as part of Parcel's TypeScript support

10

- **Engine Requirements**: Node.js >= 16.0.0, Parcel ^2.15.4

11

12

## Core Imports

13

14

This plugin is typically not imported directly by users, but rather used internally by Parcel:

15

16

```javascript

17

import {Packager} from '@parcel/plugin';

18

```

19

20

For advanced plugin development scenarios:

21

22

```javascript

23

import type {

24

PackageContext,

25

PluginOptions,

26

PluginLogger,

27

PluginTracer,

28

BundleGraph,

29

NamedBundle,

30

BundleResult

31

} from '@parcel/types';

32

```

33

34

For direct usage (advanced scenarios only):

35

36

```javascript

37

const TSPackager = require('@parcel/packager-ts');

38

// TSPackager is a configured Packager instance, not a class

39

```

40

41

## Basic Usage

42

43

This plugin operates automatically within Parcel's build pipeline when processing TypeScript files. It does not require manual configuration or direct invocation by end users.

44

45

```typescript

46

// Your TypeScript source file

47

export function greet(name: string): string {

48

return `Hello, ${name}!`;

49

}

50

51

// Parcel processes this through the TypeScript packager automatically

52

```

53

54

## Architecture

55

56

The @parcel/packager-ts plugin is part of Parcel's packaging phase, which occurs after transformation and optimization. The packaging phase combines processed assets into final bundles.

57

58

**Plugin Lifecycle:**

59

1. **Configuration Loading**: Optional `loadConfig` and `loadBundleConfig` methods can load plugin-specific configuration

60

2. **Package Execution**: The main `package` method processes bundles containing TypeScript assets

61

3. **Output Generation**: Returns packaged contents with source maps and metadata

62

63

**Integration Points:**

64

- **Bundle Graph**: Accesses the complete dependency graph and bundle relationships

65

- **Asset Processing**: Works with compiled TypeScript assets from previous build phases

66

- **Source Maps**: Integrates with Parcel's source map system for debugging support

67

- **Configuration System**: Can access both global and bundle-specific configuration

68

69

## Capabilities

70

71

### TypeScript Bundle Packaging

72

73

Processes TypeScript bundles during Parcel's packaging phase, converting compiled TypeScript assets into final JavaScript bundles with proper source map integration.

74

75

```javascript { .api }

76

/**

77

* Main packaging function that processes TypeScript bundles

78

* @param context - Complete packaging context with bundle, configuration, and utilities

79

* @returns Promise resolving to packaged bundle result with contents and source map

80

*/

81

async function package(context: PackageContext): Promise<BundleResult>;

82

83

interface PackageContext {

84

/** The bundle containing TypeScript assets to process */

85

bundle: NamedBundle;

86

/** Complete bundle graph for dependency resolution */

87

bundleGraph: BundleGraph<NamedBundle>;

88

/** Global Parcel options and configuration */

89

options: PluginOptions;

90

/** Plugin logger for diagnostics and debugging */

91

logger: PluginLogger;

92

/** Performance tracing utilities */

93

tracer: PluginTracer;

94

/** Plugin-specific configuration (from loadConfig) */

95

config: any;

96

/** Bundle-specific configuration (from loadBundleConfig) */

97

bundleConfig: any;

98

/** Function to get contents of inline bundles */

99

getInlineBundleContents: (

100

bundle: Bundle,

101

bundleGraph: BundleGraph<NamedBundle>

102

) => Promise<{contents: Blob}>;

103

/** Function to generate source map references */

104

getSourceMapReference: (map: ?SourceMap) => Promise<?string>;

105

}

106

```

107

108

The packaging process:

109

110

1. **Bundle Validation**: Ensures the bundle contains exactly one asset (TypeScript bundles must be single-asset)

111

2. **Code Extraction**: Retrieves the compiled JavaScript code from the TypeScript asset

112

3. **Source Map Processing**: Extracts the source map if available

113

4. **Source Map Reference**: Appends source map reference as a JavaScript comment if source map exists

114

5. **Result Return**: Returns the packaged contents with the source map

115

116

### Asset Processing

117

118

Individual asset processing within the bundle.

119

120

```javascript { .api }

121

interface Asset {

122

/** Retrieves the compiled JavaScript code from the asset */

123

getCode(): Promise<string>;

124

/** Retrieves the source map associated with the asset */

125

getMap(): Promise<?SourceMap>;

126

}

127

```

128

129

### Bundle Types

130

131

Core Parcel bundle interfaces used by the packager.

132

133

```javascript { .api }

134

interface Bundle {

135

/** The bundle identifier */

136

+id: string;

137

/** The bundle type (e.g., 'js') */

138

+type: string;

139

/** The target environment */

140

+env: Environment;

141

/** The bundle's target configuration */

142

+target: Target;

143

/** Whether the bundle needs a stable filename */

144

+needsStableName: ?boolean;

145

/** Controls bundle behavior (inline/isolated) */

146

+bundleBehavior: ?BundleBehavior;

147

/** Whether bundle can be split */

148

+isSplittable: ?boolean;

149

/** Placeholder for content hash */

150

+hashReference: string;

151

152

/** Returns entry assets executed when bundle loads */

153

getEntryAssets(): Array<Asset>;

154

/** Returns main entry asset providing bundle exports */

155

getMainEntry(): ?Asset;

156

/** Checks if bundle includes given asset */

157

hasAsset(Asset): boolean;

158

/** Checks if bundle includes given dependency */

159

hasDependency(Dependency): boolean;

160

/** Traverses all assets in the bundle */

161

traverseAssets<TContext>(

162

visit: GraphVisitor<Asset, TContext>,

163

startAsset?: Asset

164

): ?TContext;

165

/** Traverses assets and dependencies in bundle */

166

traverse<TContext>(

167

visit: GraphVisitor<BundleTraversable, TContext>

168

): ?TContext;

169

/** Returns hash of bundle contents */

170

getContentHash(): string;

171

}

172

173

interface NamedBundle extends Bundle {

174

/** Shortened bundle ID for runtime reference */

175

+publicId: string;

176

/** Bundle filename relative to target directory */

177

+name: string;

178

/** Display-friendly bundle name */

179

+displayName: string;

180

}

181

182

type BundleBehavior = 'inline' | 'isolated';

183

184

type GraphVisitor<TNode, TContext> = (

185

node: TNode,

186

context: TContext | null

187

) => TContext | null;

188

189

interface Environment {

190

/** Build context (e.g., 'browser', 'node') */

191

+context: string;

192

/** Target engines and versions */

193

+engines: {[string]: string};

194

/** Include node modules configuration */

195

+includeNodeModules: boolean | Array<string>;

196

/** Output format */

197

+outputFormat: string;

198

/** Source map configuration */

199

+sourceMap: ?SourceMapOptions;

200

}

201

202

interface Target {

203

/** Target name */

204

+name: string;

205

/** Distribution directory */

206

+distDir: FilePath;

207

/** Target environment */

208

+env: Environment;

209

/** Source glob patterns */

210

+source: string | Array<string>;

211

/** Location configuration */

212

+loc: ?SourceLocation;

213

}

214

215

interface SourceMapOptions {

216

/** Whether to generate source maps */

217

+enabled: boolean;

218

/** Include source maps inline in bundle */

219

+inline: boolean;

220

/** Source root path */

221

+sourceRoot?: string;

222

}

223

224

type FilePath = string;

225

type SourceLocation = {|

226

+filePath: FilePath,

227

+start: {| +line: number, +column: number |},

228

+end: {| +line: number, +column: number |},

229

|};

230

```

231

232

### Core Plugin Interfaces

233

234

Essential Parcel plugin interfaces used throughout the packaging system.

235

236

```javascript { .api }

237

interface PluginOptions {

238

/** Build mode (development/production) */

239

+mode: BuildMode;

240

/** Parcel version */

241

+parcelVersion: string;

242

/** Environment variables */

243

+env: EnvMap;

244

/** Hot module replacement options */

245

+hmrOptions: ?HMROptions;

246

/** Development server options */

247

+serveOptions: ServerOptions | false;

248

/** Lazy bundling flag */

249

+shouldBuildLazily: boolean;

250

/** Auto-install dependencies flag */

251

+shouldAutoInstall: boolean;

252

/** Logging level */

253

+logLevel: LogLevel;

254

/** Project root directory */

255

+projectRoot: FilePath;

256

/** Cache directory */

257

+cacheDir: FilePath;

258

/** Input file system */

259

+inputFS: FileSystem;

260

/** Output file system */

261

+outputFS: FileSystem;

262

/** Package manager instance */

263

+packageManager: PackageManager;

264

/** Parcel instance ID */

265

+instanceId: string;

266

/** Detailed reporting options */

267

+detailedReport: ?DetailedReportOptions;

268

/** Feature flags */

269

+featureFlags: FeatureFlags;

270

}

271

272

interface PluginLogger {

273

/** Log verbose diagnostic messages */

274

verbose(diagnostic: DiagnosticWithoutOrigin | Array<DiagnosticWithoutOrigin>): void;

275

/** Log informational messages */

276

info(diagnostic: DiagnosticWithoutOrigin | Array<DiagnosticWithoutOrigin>): void;

277

/** Log general messages */

278

log(diagnostic: DiagnosticWithoutOrigin | Array<DiagnosticWithoutOrigin>): void;

279

/** Log warning messages */

280

warn(diagnostic: DiagnosticWithoutOrigin | Array<DiagnosticWithoutOrigin>): void;

281

/** Log error messages */

282

error(input: Diagnostifiable | DiagnosticWithoutOrigin | Array<DiagnosticWithoutOrigin>): void;

283

}

284

285

interface PluginTracer {

286

/** Whether tracing is enabled */

287

+enabled: boolean;

288

/** Create a performance measurement */

289

createMeasurement(

290

name: string,

291

category?: string,

292

argumentName?: string,

293

otherArgs?: {[key: string]: mixed}

294

): TraceMeasurement | null;

295

}

296

297

interface Config {

298

/** Whether this is source-level config */

299

+isSource: boolean;

300

/** Config search path */

301

+searchPath: FilePath;

302

/** Target environment */

303

+env: Environment;

304

305

/** Invalidate cache when file changes */

306

invalidateOnFileChange(FilePath): void;

307

/** Invalidate cache when file is created */

308

invalidateOnFileCreate(FileCreateInvalidation): void;

309

/** Invalidate cache when environment variable changes */

310

invalidateOnEnvChange(string): void;

311

/** Invalidate cache on startup */

312

invalidateOnStartup(): void;

313

/** Invalidate cache on build */

314

invalidateOnBuild(): void;

315

/** Add development dependency */

316

addDevDependency(DevDepOptions): void;

317

/** Set cache key */

318

setCacheKey(string): void;

319

320

/** Get configuration from files */

321

getConfig<T>(

322

filePaths: Array<FilePath>,

323

options?: {|

324

packageKey?: string,

325

parse?: boolean,

326

exclude?: boolean,

327

|}

328

): Promise<?ConfigResultWithFilePath<T>>;

329

330

/** Get configuration from specific search path */

331

getConfigFrom<T>(

332

searchPath: FilePath,

333

filePaths: Array<FilePath>,

334

options?: {|

335

packageKey?: string,

336

parse?: boolean,

337

exclude?: boolean,

338

|}

339

): Promise<?ConfigResultWithFilePath<T>>;

340

341

/** Get package.json */

342

getPackage(): Promise<?PackageJSON>;

343

}

344

345

type Blob = string | Buffer | Readable;

346

type BuildMode = 'development' | 'production';

347

type LogLevel = 'none' | 'error' | 'warn' | 'info' | 'verbose';

348

```

349

350

### Bundle Graph Interface

351

352

The BundleGraph provides access to the complete dependency graph and bundle relationships.

353

354

```javascript { .api }

355

interface BundleGraph<TBundle: Bundle> {

356

/** Get asset by ID */

357

getAssetById(id: string): Asset;

358

/** Get public ID for asset */

359

getAssetPublicId(asset: Asset): string;

360

/** Get all bundles */

361

getBundles(opts?: {|includeInline: boolean|}): Array<TBundle>;

362

363

/** Traverse bundle graph */

364

traverse<TContext>(

365

visit: GraphVisitor<BundleGraphTraversable, TContext>,

366

startAsset: ?Asset,

367

options?: {|skipUnusedDependencies?: boolean|}

368

): ?TContext;

369

370

/** Traverse bundles */

371

traverseBundles<TContext>(

372

visit: GraphVisitor<TBundle, TContext>,

373

startBundle: ?Bundle

374

): ?TContext;

375

376

/** Get bundle groups containing bundle */

377

getBundleGroupsContainingBundle(bundle: Bundle): Array<BundleGroup>;

378

/** Get bundles in bundle group */

379

getBundlesInBundleGroup(bundleGroup: BundleGroup): Array<TBundle>;

380

/** Get child bundles */

381

getChildBundles(bundle: Bundle): Array<TBundle>;

382

/** Get parent bundles */

383

getParentBundles(bundle: Bundle): Array<TBundle>;

384

385

/** Get dependencies for asset */

386

getDependencies(asset: Asset): Array<Dependency>;

387

/** Get incoming dependencies for asset */

388

getIncomingDependencies(asset: Asset): Array<Dependency>;

389

/** Get asset with dependency */

390

getAssetWithDependency(dep: Dependency): ?Asset;

391

/** Get resolved asset for dependency */

392

getResolvedAsset(dependency: Dependency, bundle: ?Bundle): ?Asset;

393

}

394

```

395

396

### Result Types

397

398

The packager returns structured results containing the final bundle output.

399

400

```javascript { .api }

401

interface BundleResult {

402

/** The final packaged contents as a Blob */

403

+contents: Blob;

404

/** Optional AST representation */

405

+ast?: AST;

406

/** Optional source map */

407

+map?: ?SourceMap;

408

/** Optional content type override */

409

+type?: string;

410

}

411

```

412

413

### Packager Plugin Interface

414

415

Base interface for Parcel packager plugins.

416

417

```javascript { .api }

418

class Packager {

419

/**

420

* Creates a new packager plugin instance

421

* @param opts - Packager configuration options

422

*/

423

constructor<ConfigType, BundleConfigType>(opts: PackagerOpts<ConfigType, BundleConfigType>);

424

}

425

426

interface PackagerOpts<ConfigType, BundleConfigType> {

427

/** Optional configuration loader executed during plugin initialization */

428

loadConfig?: (context: LoadConfigContext) => Promise<ConfigType>;

429

/** Optional bundle-specific configuration loader */

430

loadBundleConfig?: (context: LoadBundleConfigContext) => Promise<BundleConfigType>;

431

/** Main packaging function (required) */

432

package(context: PackageContext<ConfigType, BundleConfigType>): Promise<BundleResult | BundleResult[]>;

433

}

434

435

interface LoadConfigContext {

436

/** Configuration management utilities */

437

config: Config;

438

/** Global Parcel options */

439

options: PluginOptions;

440

/** Plugin logger instance */

441

logger: PluginLogger;

442

/** Performance tracer */

443

tracer: PluginTracer;

444

}

445

446

interface LoadBundleConfigContext {

447

/** The specific bundle being configured */

448

bundle: NamedBundle;

449

/** Complete bundle graph */

450

bundleGraph: BundleGraph<NamedBundle>;

451

/** Configuration management utilities */

452

config: Config;

453

/** Global Parcel options */

454

options: PluginOptions;

455

/** Plugin logger instance */

456

logger: PluginLogger;

457

/** Performance tracer */

458

tracer: PluginTracer;

459

}

460

```

461

462

## Error Handling

463

464

The packager performs validation and will throw errors in specific scenarios:

465

466

- **Multiple Assets**: Throws assertion error if a TypeScript bundle contains more than one asset

467

- **Zero Assets**: Throws assertion error if a TypeScript bundle contains no assets

468

469

## Source Map Integration

470

471

When source maps are available, the packager automatically appends source map references using standard JavaScript comment syntax:

472

473

```javascript

474

// Generated bundle content

475

export function greet(name) { return `Hello, ${name}!`; }

476

//# sourceMappingURL=bundle.js.map

477

```

478

479

## Plugin Registration

480

481

This packager is automatically registered by Parcel for TypeScript file processing. Manual registration is not required for typical usage.

482

483

## Dependencies

484

485

- **@parcel/plugin**: Provides the base Packager class and plugin framework

486

- **assert**: Node.js built-in module for bundle validation