0
# Bundler API
1
2
The Bundler class is the main entry point for programmatic control over the Parcel bundling process. It provides methods for configuration, lifecycle management, and custom asset processing.
3
4
## Capabilities
5
6
### Bundler Constructor
7
8
Creates a new Bundler instance with entry files and configuration options.
9
10
```javascript { .api }
11
/**
12
* Creates a new Bundler instance
13
* @param entryFiles - Entry file paths or glob patterns (string or array)
14
* @param options - Bundler configuration options
15
*/
16
constructor(entryFiles, options = {})
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
const Bundler = require('parcel-bundler');
23
24
// Single entry file
25
const bundler = new Bundler('./src/index.html');
26
27
// Multiple entry files
28
const bundler = new Bundler(['./src/index.html', './src/about.html']);
29
30
// With options
31
const bundler = new Bundler('./src/index.html', {
32
outDir: './dist',
33
cache: true,
34
minify: true,
35
target: 'browser'
36
});
37
38
// Glob patterns
39
const bundler = new Bundler('./src/**/*.html');
40
```
41
42
### Bundle Method
43
44
Starts the bundling process and returns the main bundle.
45
46
```javascript { .api }
47
/**
48
* Start bundling process and return the main bundle
49
* @returns Promise<Bundle> - Promise resolving to the main bundle
50
*/
51
bundle()
52
```
53
54
**Usage Examples:**
55
56
```javascript
57
// Build once
58
const bundle = await bundler.bundle();
59
console.log('Bundle generated:', bundle.name);
60
61
// Access bundle information
62
console.log('Bundle type:', bundle.type);
63
console.log('Assets count:', bundle.assets.size);
64
console.log('Child bundles:', bundle.childBundles.size);
65
```
66
67
### Development Server
68
69
Starts a development server with hot module replacement.
70
71
```javascript { .api }
72
/**
73
* Start development server with HMR
74
* @param port - Port number (default: 1234)
75
* @param https - Enable HTTPS (default: false)
76
* @param host - Host address (default: 'localhost')
77
* @returns Promise<Server> - Promise resolving to the server instance
78
*/
79
serve(port = 1234, https = false, host = 'localhost')
80
```
81
82
**Usage Examples:**
83
84
```javascript
85
// Basic development server
86
const server = await bundler.serve();
87
console.log('Server running on http://localhost:1234');
88
89
// Custom port and host
90
const server = await bundler.serve(3000, false, '0.0.0.0');
91
console.log('Server running on http://0.0.0.0:3000');
92
93
// HTTPS server
94
const server = await bundler.serve(1234, true);
95
console.log('Secure server running on https://localhost:1234');
96
```
97
98
### Express Middleware
99
100
Returns Express middleware for integrating with existing servers.
101
102
```javascript { .api }
103
/**
104
* Get Express middleware for integrating with existing servers
105
* @returns Middleware function compatible with Express
106
*/
107
middleware()
108
```
109
110
**Usage Examples:**
111
112
```javascript
113
const express = require('express');
114
const app = express();
115
116
// Add Parcel middleware to existing Express app
117
app.use(bundler.middleware());
118
119
// Add other routes
120
app.get('/api/health', (req, res) => {
121
res.json({ status: 'ok' });
122
});
123
124
app.listen(3000);
125
```
126
127
### Lifecycle Management
128
129
Methods for starting and stopping the bundler.
130
131
```javascript { .api }
132
/**
133
* Initialize bundler (worker farm, watcher, HMR)
134
* @returns Promise<void>
135
*/
136
start()
137
138
/**
139
* Stop bundler and cleanup resources
140
* @returns Promise<void>
141
*/
142
stop()
143
```
144
145
**Usage Examples:**
146
147
```javascript
148
// Manual lifecycle control
149
await bundler.start();
150
console.log('Bundler initialized');
151
152
// Do work...
153
const bundle = await bundler.bundle();
154
155
// Cleanup
156
await bundler.stop();
157
console.log('Bundler stopped');
158
```
159
160
### Asset Type Registration
161
162
Register custom asset types for handling new file extensions.
163
164
```javascript { .api }
165
/**
166
* Register custom asset type for file extension
167
* @param extension - File extension (including dot, e.g., '.custom')
168
* @param path - Path to asset class module
169
*/
170
addAssetType(extension, path)
171
```
172
173
**Usage Examples:**
174
175
```javascript
176
// Register custom asset type
177
bundler.addAssetType('.proto', require.resolve('./ProtoAsset'));
178
179
// Register multiple asset types
180
bundler.addAssetType('.graphql', require.resolve('./GraphQLAsset'));
181
bundler.addAssetType('.md', require.resolve('./MarkdownAsset'));
182
```
183
184
### Packager Registration
185
186
Register custom packagers for generating output bundles.
187
188
```javascript { .api }
189
/**
190
* Register custom packager for bundle type
191
* @param type - Bundle type (e.g., 'js', 'css', 'html')
192
* @param packager - Packager class or path to packager module
193
*/
194
addPackager(type, packager)
195
```
196
197
**Usage Examples:**
198
199
```javascript
200
const CustomPackager = require('./CustomPackager');
201
202
// Register custom packager
203
bundler.addPackager('custom', CustomPackager);
204
205
// Register packager by path
206
bundler.addPackager('special', require.resolve('./SpecialPackager'));
207
```
208
209
### Bundle Loader Registration
210
211
Register bundle loaders for different environments.
212
213
```javascript { .api }
214
/**
215
* Register bundle loader for runtime loading
216
* @param type - Bundle type (e.g., 'js', 'css', 'wasm')
217
* @param paths - Loader paths for different environments
218
*/
219
addBundleLoader(type, paths)
220
```
221
222
**Usage Examples:**
223
224
```javascript
225
// Register bundle loader for custom type
226
bundler.addBundleLoader('wasm', {
227
browser: require.resolve('./loaders/browser/wasm-loader'),
228
node: require.resolve('./loaders/node/wasm-loader')
229
});
230
231
// Register CSS loader
232
bundler.addBundleLoader('css', {
233
browser: require.resolve('./loaders/browser/css-loader'),
234
node: require.resolve('./loaders/node/css-loader')
235
});
236
```
237
238
### Asset Retrieval
239
240
Get and process specific assets.
241
242
```javascript { .api }
243
/**
244
* Get and process specific asset
245
* @param name - Asset file path
246
* @param parent - Parent asset (optional)
247
* @returns Promise<Asset> - Promise resolving to processed asset
248
*/
249
getAsset(name, parent)
250
```
251
252
**Usage Examples:**
253
254
```javascript
255
// Get specific asset
256
const asset = await bundler.getAsset('./src/components/App.js');
257
console.log('Asset type:', asset.type);
258
console.log('Asset dependencies:', asset.dependencies.size);
259
260
// Get asset relative to parent
261
const parentAsset = await bundler.getAsset('./src/index.js');
262
const childAsset = await bundler.getAsset('./utils/helper.js', parentAsset);
263
```
264
265
## Events
266
267
The Bundler class extends EventEmitter and emits the following events:
268
269
```javascript { .api }
270
/**
271
* Bundler Events
272
*/
273
interface BundlerEvents {
274
/** Emitted when build starts */
275
'buildStart': (entryFiles: string[]) => void;
276
277
/** Emitted when build ends */
278
'buildEnd': () => void;
279
280
/** Emitted when bundling succeeds */
281
'bundled': (bundle: Bundle) => void;
282
283
/** Emitted when build fails */
284
'buildError': (error: Error) => void;
285
}
286
```
287
288
**Usage Examples:**
289
290
```javascript
291
// Listen to build events
292
bundler.on('buildStart', (entryFiles) => {
293
console.log('Build started for:', entryFiles);
294
});
295
296
bundler.on('buildEnd', () => {
297
console.log('Build completed');
298
});
299
300
bundler.on('bundled', (bundle) => {
301
console.log('Bundle created:', bundle.name, bundle.assets.size);
302
});
303
304
bundler.on('buildError', (error) => {
305
console.error('Build failed:', error.message);
306
});
307
```
308
309
## Properties
310
311
Key properties available on Bundler instances:
312
313
```javascript { .api }
314
interface BundlerProperties {
315
/** Root bundle after bundling */
316
mainBundle: Bundle | null;
317
318
/** Normalized bundler options */
319
options: BundlerOptions;
320
321
/** Map of loaded assets by file path */
322
loadedAssets: Map<string, Asset>;
323
324
/** Set of entry point assets */
325
entryAssets: Set<Asset>;
326
327
/** Map of bundle names to bundle instances */
328
bundleNameMap: Map<string, Bundle>;
329
}
330
```
331
332
**Usage Examples:**
333
334
```javascript
335
// Access main bundle after bundling
336
await bundler.bundle();
337
console.log('Main bundle:', bundler.mainBundle.name);
338
339
// Check loaded assets
340
console.log('Loaded assets count:', bundler.loadedAssets.size);
341
342
// Access entry assets
343
bundler.entryAssets.forEach(asset => {
344
console.log('Entry asset:', asset.name);
345
});
346
347
// Check bundler configuration
348
console.log('Output directory:', bundler.options.outDir);
349
console.log('Cache enabled:', bundler.options.cache);
350
```
351
352
## Static Properties
353
354
Access to base classes for extending Parcel:
355
356
```javascript { .api }
357
interface BundlerStatic {
358
/** Base Asset class for creating custom asset types */
359
Asset: typeof Asset;
360
361
/** Base Packager class for creating custom packagers */
362
Packager: typeof Packager;
363
}
364
```
365
366
**Usage Examples:**
367
368
```javascript
369
const Bundler = require('parcel-bundler');
370
371
// Create custom asset type
372
class CustomAsset extends Bundler.Asset {
373
async parse(code) {
374
// Custom parsing logic
375
return customParser(code);
376
}
377
378
generate() {
379
// Custom generation logic
380
return { js: this.generateJS() };
381
}
382
}
383
384
// Create custom packager
385
class CustomPackager extends Bundler.Packager {
386
async addAsset(asset) {
387
// Custom asset addition logic
388
await this.writeAsset(asset);
389
}
390
}
391
392
// Register the custom asset type
393
const bundler = new Bundler('./src/index.html');
394
bundler.addAssetType('.custom', CustomAsset);
395
396
// Access base classes
397
console.log(Bundler.Asset); // Asset constructor
398
console.log(Bundler.Packager); // Packager constructor
399
```
400
401
## Configuration Options
402
403
Complete reference for Bundler constructor options:
404
405
```javascript { .api }
406
interface BundlerOptions {
407
/** Output directory (default: 'dist') */
408
outDir?: string;
409
410
/** Output filename (overrides default naming) */
411
outFile?: string;
412
413
/** Public URL path for assets (default: '/') */
414
publicURL?: string;
415
416
/** Enable file watching for development */
417
watch?: boolean;
418
419
/** Enable build caching (default: true) */
420
cache?: boolean;
421
422
/** Cache directory (default: '.cache') */
423
cacheDir?: string;
424
425
/** Enable minification for production builds */
426
minify?: boolean;
427
428
/** Build target: 'browser', 'node', or 'electron' */
429
target?: 'browser' | 'node' | 'electron';
430
431
/** Bundle node_modules dependencies */
432
bundleNodeModules?: boolean;
433
434
/** Enable hot module replacement */
435
hmr?: boolean;
436
437
/** HTTPS configuration for dev server */
438
https?: boolean | { cert: string; key: string };
439
440
/** Generate source maps (default: true) */
441
sourceMaps?: boolean;
442
443
/** Logging level (0=silent, 5=verbose) */
444
logLevel?: 0 | 1 | 2 | 3 | 4 | 5;
445
446
/** Auto-install missing dependencies */
447
autoinstall?: boolean;
448
449
/** Enable scope hoisting/tree shaking */
450
scopeHoist?: boolean;
451
452
/** Enable content hashing in filenames */
453
contentHash?: boolean;
454
455
/** Production mode (sets minify, sourceMaps, etc.) */
456
production?: boolean;
457
}
458
```