CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-parcel-bundler

Blazing fast, zero configuration web application bundler

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

bundler-api.mddocs/

Bundler API

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.

Capabilities

Bundler Constructor

Creates a new Bundler instance with entry files and configuration options.

/**
 * Creates a new Bundler instance
 * @param entryFiles - Entry file paths or glob patterns (string or array)
 * @param options - Bundler configuration options
 */
constructor(entryFiles, options = {})

Usage Examples:

const Bundler = require('parcel-bundler');

// Single entry file
const bundler = new Bundler('./src/index.html');

// Multiple entry files
const bundler = new Bundler(['./src/index.html', './src/about.html']);

// With options
const bundler = new Bundler('./src/index.html', {
  outDir: './dist',
  cache: true,
  minify: true,
  target: 'browser'
});

// Glob patterns
const bundler = new Bundler('./src/**/*.html');

Bundle Method

Starts the bundling process and returns the main bundle.

/**
 * Start bundling process and return the main bundle
 * @returns Promise<Bundle> - Promise resolving to the main bundle
 */
bundle()

Usage Examples:

// Build once
const bundle = await bundler.bundle();
console.log('Bundle generated:', bundle.name);

// Access bundle information
console.log('Bundle type:', bundle.type);
console.log('Assets count:', bundle.assets.size);
console.log('Child bundles:', bundle.childBundles.size);

Development Server

Starts a development server with hot module replacement.

/**
 * Start development server with HMR
 * @param port - Port number (default: 1234)
 * @param https - Enable HTTPS (default: false)
 * @param host - Host address (default: 'localhost')
 * @returns Promise<Server> - Promise resolving to the server instance
 */
serve(port = 1234, https = false, host = 'localhost')

Usage Examples:

// Basic development server
const server = await bundler.serve();
console.log('Server running on http://localhost:1234');

// Custom port and host
const server = await bundler.serve(3000, false, '0.0.0.0');
console.log('Server running on http://0.0.0.0:3000');

// HTTPS server
const server = await bundler.serve(1234, true);
console.log('Secure server running on https://localhost:1234');

Express Middleware

Returns Express middleware for integrating with existing servers.

/**
 * Get Express middleware for integrating with existing servers
 * @returns Middleware function compatible with Express
 */
middleware()

Usage Examples:

const express = require('express');
const app = express();

// Add Parcel middleware to existing Express app
app.use(bundler.middleware());

// Add other routes
app.get('/api/health', (req, res) => {
  res.json({ status: 'ok' });
});

app.listen(3000);

Lifecycle Management

Methods for starting and stopping the bundler.

/**
 * Initialize bundler (worker farm, watcher, HMR)
 * @returns Promise<void>
 */
start()

/**
 * Stop bundler and cleanup resources
 * @returns Promise<void>
 */
stop()

Usage Examples:

// Manual lifecycle control
await bundler.start();
console.log('Bundler initialized');

// Do work...
const bundle = await bundler.bundle();

// Cleanup
await bundler.stop();
console.log('Bundler stopped');

Asset Type Registration

Register custom asset types for handling new file extensions.

/**
 * Register custom asset type for file extension
 * @param extension - File extension (including dot, e.g., '.custom')
 * @param path - Path to asset class module
 */
addAssetType(extension, path)

Usage Examples:

// Register custom asset type
bundler.addAssetType('.proto', require.resolve('./ProtoAsset'));

// Register multiple asset types
bundler.addAssetType('.graphql', require.resolve('./GraphQLAsset'));
bundler.addAssetType('.md', require.resolve('./MarkdownAsset'));

Packager Registration

Register custom packagers for generating output bundles.

/**
 * Register custom packager for bundle type
 * @param type - Bundle type (e.g., 'js', 'css', 'html')
 * @param packager - Packager class or path to packager module
 */
addPackager(type, packager)

Usage Examples:

const CustomPackager = require('./CustomPackager');

// Register custom packager
bundler.addPackager('custom', CustomPackager);

// Register packager by path
bundler.addPackager('special', require.resolve('./SpecialPackager'));

Bundle Loader Registration

Register bundle loaders for different environments.

/**
 * Register bundle loader for runtime loading
 * @param type - Bundle type (e.g., 'js', 'css', 'wasm')
 * @param paths - Loader paths for different environments
 */
addBundleLoader(type, paths)

Usage Examples:

// Register bundle loader for custom type
bundler.addBundleLoader('wasm', {
  browser: require.resolve('./loaders/browser/wasm-loader'),
  node: require.resolve('./loaders/node/wasm-loader')
});

// Register CSS loader
bundler.addBundleLoader('css', {
  browser: require.resolve('./loaders/browser/css-loader'),
  node: require.resolve('./loaders/node/css-loader')
});

Asset Retrieval

Get and process specific assets.

/**
 * Get and process specific asset
 * @param name - Asset file path
 * @param parent - Parent asset (optional)
 * @returns Promise<Asset> - Promise resolving to processed asset
 */
getAsset(name, parent)

Usage Examples:

// Get specific asset
const asset = await bundler.getAsset('./src/components/App.js');
console.log('Asset type:', asset.type);
console.log('Asset dependencies:', asset.dependencies.size);

// Get asset relative to parent
const parentAsset = await bundler.getAsset('./src/index.js');
const childAsset = await bundler.getAsset('./utils/helper.js', parentAsset);

Events

The Bundler class extends EventEmitter and emits the following events:

/**
 * Bundler Events
 */
interface BundlerEvents {
  /** Emitted when build starts */
  'buildStart': (entryFiles: string[]) => void;
  
  /** Emitted when build ends */
  'buildEnd': () => void;
  
  /** Emitted when bundling succeeds */
  'bundled': (bundle: Bundle) => void;
  
  /** Emitted when build fails */
  'buildError': (error: Error) => void;
}

Usage Examples:

// Listen to build events
bundler.on('buildStart', (entryFiles) => {
  console.log('Build started for:', entryFiles);
});

bundler.on('buildEnd', () => {
  console.log('Build completed');
});

bundler.on('bundled', (bundle) => {
  console.log('Bundle created:', bundle.name, bundle.assets.size);
});

bundler.on('buildError', (error) => {
  console.error('Build failed:', error.message);
});

Properties

Key properties available on Bundler instances:

interface BundlerProperties {
  /** Root bundle after bundling */
  mainBundle: Bundle | null;
  
  /** Normalized bundler options */
  options: BundlerOptions;
  
  /** Map of loaded assets by file path */
  loadedAssets: Map<string, Asset>;
  
  /** Set of entry point assets */
  entryAssets: Set<Asset>;
  
  /** Map of bundle names to bundle instances */
  bundleNameMap: Map<string, Bundle>;
}

Usage Examples:

// Access main bundle after bundling
await bundler.bundle();
console.log('Main bundle:', bundler.mainBundle.name);

// Check loaded assets
console.log('Loaded assets count:', bundler.loadedAssets.size);

// Access entry assets
bundler.entryAssets.forEach(asset => {
  console.log('Entry asset:', asset.name);
});

// Check bundler configuration
console.log('Output directory:', bundler.options.outDir);
console.log('Cache enabled:', bundler.options.cache);

Static Properties

Access to base classes for extending Parcel:

interface BundlerStatic {
  /** Base Asset class for creating custom asset types */
  Asset: typeof Asset;
  
  /** Base Packager class for creating custom packagers */
  Packager: typeof Packager;
}

Usage Examples:

const Bundler = require('parcel-bundler');

// Create custom asset type
class CustomAsset extends Bundler.Asset {
  async parse(code) {
    // Custom parsing logic
    return customParser(code);
  }
  
  generate() {
    // Custom generation logic
    return { js: this.generateJS() };
  }
}

// Create custom packager
class CustomPackager extends Bundler.Packager {
  async addAsset(asset) {
    // Custom asset addition logic
    await this.writeAsset(asset);
  }
}

// Register the custom asset type
const bundler = new Bundler('./src/index.html');
bundler.addAssetType('.custom', CustomAsset);

// Access base classes
console.log(Bundler.Asset); // Asset constructor
console.log(Bundler.Packager); // Packager constructor

Configuration Options

Complete reference for Bundler constructor options:

interface BundlerOptions {
  /** Output directory (default: 'dist') */
  outDir?: string;
  
  /** Output filename (overrides default naming) */
  outFile?: string;
  
  /** Public URL path for assets (default: '/') */
  publicURL?: string;
  
  /** Enable file watching for development */
  watch?: boolean;
  
  /** Enable build caching (default: true) */
  cache?: boolean;
  
  /** Cache directory (default: '.cache') */
  cacheDir?: string;
  
  /** Enable minification for production builds */
  minify?: boolean;
  
  /** Build target: 'browser', 'node', or 'electron' */
  target?: 'browser' | 'node' | 'electron';
  
  /** Bundle node_modules dependencies */
  bundleNodeModules?: boolean;
  
  /** Enable hot module replacement */
  hmr?: boolean;
  
  /** HTTPS configuration for dev server */
  https?: boolean | { cert: string; key: string };
  
  /** Generate source maps (default: true) */
  sourceMaps?: boolean;
  
  /** Logging level (0=silent, 5=verbose) */
  logLevel?: 0 | 1 | 2 | 3 | 4 | 5;
  
  /** Auto-install missing dependencies */
  autoinstall?: boolean;
  
  /** Enable scope hoisting/tree shaking */
  scopeHoist?: boolean;
  
  /** Enable content hashing in filenames */
  contentHash?: boolean;
  
  /** Production mode (sets minify, sourceMaps, etc.) */
  production?: boolean;
}

Install with Tessl CLI

npx tessl i tessl/npm-parcel-bundler

docs

asset-system.md

bundler-api.md

cli.md

index.md

tile.json